如何限制从浏览器直接上传到通过预签名 URL 保护的 S3 的内容类型?

问题描述 投票: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
投票

您需要使用

createPresignedPost
,文章中段对此进行了描述,网址为 https://medium.com/@Games24x7Tech/a-complete-guide-to-s3-file-upload-using-pre-signed-post- urls-9cb2d6cfc0ab,而不是
PutObjectCommand()

基于误解问题的旧答案:

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

来源:第一手经验。我保存了一些没有这些标头的

.json.gz
对象,当我尝试打开 URL 时,它不会在屏幕上显示 json,而是会弹出“下载”或“另存为”对话框。

如果您有

.jpg
图像并且想要在网络浏览器中显示该图像而不是强制用户将其下载为文件,则可能会发生相同的情况。

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