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.
You don't need to use a FormData, just pass the file with an 'octet-stream' content type.
acl must be used when generating the presign url.
fetch(url, { method: 'PUT', body: file, headers: { 'Content-Type': 'application/octet-stream' } })