为什么在使用 nodejs 和 aws-s3 生成 uplaod presignedURL 时发送内容类型被视为良好实践

问题描述 投票:0回答:1

我正在尝试生成一个上传预签名网址,其中前端需要发送文件的内容类型。
我发现如果前端不发送此内容类型并且我删除了参数中的内容类型,一切正常,
但在存储桶中,对象的类型为空白,未提及类型。
所以我认为在下载或通过 presignedurl 获取对象并获取它时会出现一些错误
但一切仍然正常
我唯一能想到的是我们可以在后端使用该内容类型进行验证,并可以将上传限制为特定内容类型,例如图像视频或其他内容?
谁能解释一下真实的用例
谢谢。

app.post("/api/posts/pre", async (req, res) => {
  const bucketName = 'usman.test.bucket';
  const { fileName, fileType } = req.body; // Get file name and file type from form data
// /frontend is responsible for providing the fileType information, while the backend handles the generation of the fileName and the pre-signed URL. This separation of concerns ensures that the application is more modular and maintainable.
// /If the frontend doesn't provide the fileType, the backend can assume a default file type, such as application/octet-stream, which is a generic binary file type.
  try {
    const params = {
      Bucket: bucketName,
      Key: fileName,
      ContentType: fileType,
    };

    const command = new PutObjectCommand(params);
    const signedUrl = await getSignedUrl(s3, command, { expiresIn: 3600 });

    res.json({ presignedUrl: signedUrl });
  } catch (error) {
    console.error('Error generating pre-signed URL:', error);
    res.status(500).send('Error generating pre-signed URL');
  }
});
node.js express amazon-s3 mime-types pre-signed-url
1个回答
0
投票

当您直接在浏览器中打开 S3 中的文件时,如果您具有正确的内容类型和编码,效果会更好。

使用 json.gz 文件亲自尝试一下。来源:我自己尝试过。

© www.soinside.com 2019 - 2024. All rights reserved.