Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload photo to AWS S3 using the Fetch API?

I am trying to upload a photo file to an S3 bucket using the Fetch API. I'm getting 400 Bad Request on the POST when trying to upload the photo. I am getting the presigned post url and the file details correctly but I believe the way I am formatting the formData is incorrect.

I'm using an html file input that uses onchange to run a javascript function handlePhoto.

The html is

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

and javascript function is

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"
        }
      })
  });
}

Any help would be greatly appreciated.

like image 310
Jordan Greenberg Avatar asked Dec 06 '25 03:12

Jordan Greenberg


1 Answers

Assuming you have a presigned url you could use something like this:

interface UploadToS3Params {
  url: string;
  file: File;
}

export function uploadToS3(params: UploadToS3Params) {
  const { file, url } = params;
  return fetch(url, {
    body: file,
    mode: "cors",
    method: "PUT",
    // optional headers
    // headers: { "Content-Type": "text/plain" },
  });
}
like image 156
Ben Stickley Avatar answered Dec 07 '25 20:12

Ben Stickley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!