【问题标题】:How to upload photo to AWS S3 using the Fetch API?如何使用 Fetch API 将照片上传到 AWS S3?
【发布时间】:2020-08-22 04:58:24
【问题描述】:

我正在尝试使用 Fetch API 将照片文件上传到 S3 存储桶。尝试上传照片时,我在 POST 上收到 400 Bad Request。我正确地获取了预签名的帖子 url 和文件详细信息,但我相信我格式化 formData 的方式不正确。

我正在使用一个 html 文件输入,它使用 onchange 来运行一个 javascript 函数 handlePhoto。

html是

<input type="file" onchange="handlePhoto()" id="file_input"/>

和javascript函数是

function handlePhoto(){
    const file = document.getElementById('file_input').files[0]
    let formData = new FormData()
    fetch("/v1/photos/get_presigned_post/" , {
      method: "GET"
    })
    .then(response => response.json())
    .then(s3Result => {
      const { url, fields } = s3Result;
      Object.keys(s3Result.fields).forEach(key => {
        formData.append(key, s3Result.fields[key]);
      });
      formData.append('acl', 'public-read');
      formData.append('Content-Type', file.type);
      formData.append("file", file);

      fetch(url, {
        method: "POST",
        body: formData,
        headers: {
          "Content-Type": "multipart/form-data"
        }
      })
  });
}

任何帮助将不胜感激。

【问题讨论】:

  • 不要使用mode: "no-cors"。 S3 API 支持 CORS 访问
  • 你怎么知道你的 POST 请求的响应是什么?您根本没有任何东西处理响应。如果你能以某种方式看到响应状态,那么响应文本是什么?
  • 我可以在浏览器中使用 Chrome 开发者工具查看请求标头和有效负载。这些屏幕截图中链接了信息。标头:i.imgur.com/FptTWU7.png 请求负载:i.imgur.com/jaN61lo.png

标签: javascript amazon-web-services amazon-s3 fetch-api


【解决方案1】:

您不需要使用 FormData,只需传递内容类型为“八位字节流”的文件即可。

生成presign URL时必须使用acl。

fetch(url, {
                method: 'PUT',
                body: file,
                headers: { 'Content-Type': 'application/octet-stream' }
            })

【讨论】:

    猜你喜欢
    • 2018-08-29
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 2020-04-25
    • 2022-12-16
    • 1970-01-01
    相关资源
    最近更新 更多