如何使用 Fetch API 将照片上传到 AWS S3?

Jor*_*erg 7 javascript amazon-s3 amazon-web-services fetch-api

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

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

html是

<input type="file" onchange="handlePhoto()" id="file_input"/>
Run Code Online (Sandbox Code Playgroud)

和 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"
        }
      })
  });
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。

gui*_*e06 -2

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

生成预签名 URL 时必须使用 acl。

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