I am trying to upload a file to s3 with direct browser upload using ajax
Here is my html
<form id="upload" action="//s3-ap-south-1.amazonaws.com/cushbudirect" method="POST" enctype="multipart/form-data">
<input type="hidden" name="Content-Type" value="multipart/form-data" />
<input type="hidden" name="acl" value="private" />
<input type="hidden" name="success_action_status" value="201" />
<input type="hidden" name="policy" value="eyJleHBpcmF0aW9uIjoiMjAxNy0wMy0yMVQxNDoxMTozMFoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJjdXNoYnVkaXJlY3QifSx7ImFjbCI6InByaXZhdGUifSxbInN0YXJ0cy13aXRoIiwiJGtleSIsIiJdLFsiZXEiLCIkQ29udGVudC1UeXBlIiwibXVsdGlwYXJ0XC9mb3JtLWRhdGEiXSxbImNvbnRlbnQtbGVuZ3RoLXJhbmdlIiwwLDUyNDI4ODAwMF0seyJzdWNjZXNzX2FjdGlvbl9zdGF0dXMiOiIyMDEifSx7IngtYW16LWNyZWRlbnRpYWwiOiJBS0lBSlJWRVhVVFRWTjROWUFSUVwvMjAxNzAzMjFcL2FwLXNvdXRoLTFcL3MzXC9hd3M0X3JlcXVlc3QifSx7IngtYW16LWFsZ29yaXRobSI6IkFXUzQtSE1BQy1TSEEyNTYifSx7IngtYW16LWRhdGUiOiIyMDE3MDMyMVQwODExMzBaIn1dfQ==" />
<input type="hidden" name="X-amz-credential" value="AKIAJRVEXUTTVN4NYAQ/20170321/ap-south-1/s3/aws4_request" />
<input type="hidden" name="X-amz-algorithm" value="AWS4-HMAC-SHA256" />
<input type="hidden" name="X-amz-date" value="20170321T081130Z" />
<input type="hidden" name="X-amz-signature" value="152c81d87fc8bbf2642e26b28f1c41b361e7285e835971b10c74ee6d7f03b5" />
<input type="hidden" name="key" value="hello.jpg" />
<input type="file" name="file" id="image">
<input type="submit" value="upload" name="upload">
</form>
Js
$('#upload').submit(function (e) {
e.preventDefault();
//get form data
var data= new FormData($("#upload")[0]);
console.log(JSON.stringify(data));
$.ajax({
url:$(this).attr('action'),
method:"post",
processData:false,
data:image,
contentType:'multipart/form-data',
success:function (data) {
console.log(JSON.stringify(data));
},
error:function (err) {
console.log(JSON.stringify(err));
}
})
});
But i got the following error from the aws xml error response .
The body of your POST request is not well-formed multipart/form-data.
I've tried the solutions from similar questions but none of them worked for me.
However when i try to upload without ajax(Normal formsubmit) the uploads works fine,
So i am sure about its the problem with form data
console.log(JSON.stringify(data)); returns {}.
Try to change your ajax function as given below and let me know if it works.
EDIT:
$('#upload').submit(function (e) {
e.preventDefault();
//get form data
var data = new FormData($("#upload")[0]);
console.log(JSON.stringify(data));
$.ajax({
url:$(this).attr('action'),
type : 'PUT',
processData:false,
data:data,
contentType:data.type,
success:function (data) {
console.log(JSON.stringify(data));
},
error:function (err) {
console.log(JSON.stringify(err));
}
})
});