MZH
MZH

Reputation: 1514

Upload Directly to amazon S3 using AJAX returning error: Bucket POST must contain a field named 'key'

I'm trying to upload files from browser to s3 amazon, I've modified the CORS policy rules to allow the post for the bucket, but I'm getting the error

    <?xml version="1.0" encoding="UTF-8"?>
    <Error><Code>InvalidArgument</Code><Message>Bucket POST must contain a field named 'key'.  If it is specified, please check the order of the fields.</Message>
<ArgumentValue></ArgumentValue><ArgumentName>key</ArgumentName><RequestId>1E0A8DC78C0CEA9A</RequestId><HostId>XN38Qje9hUrGqHNIhtT8CtowX9tXlpyfEoaXb1UNxlsyLOWreh2mKqKVXg1zjLVl</HostId></Error>

Here is my request and response, I'm passing key parameter in the right order by still getting this error

http://screencast.com/t/9ZUQO0s9d

http://screencast.com/t/CL8MKq6l6

Can anyone tell me whats wrong with it, I'm submitting request using FormData

any help would be greatly appreciated.

Thanks

Edit: here is the code pls check

var form_data = new FormData();         
                form_data.append('file',hdlr.file);
                //form_data.append('crop_type',settings.get_cropped_type());
                //form_data.append('attributes',JSON.stringify(file_attr));
                $('input:hidden',$form).each(function(){

                    form_data.append(this.name,this.value);

                });


                //finally post the file through AJAX  
                var xhr = new XMLHttpRequest();  
                xhr.open("POST", $form[0].action, true);  
                xhr.send(form_data);

enter image description here

Upvotes: 22

Views: 14505

Answers (2)

Manh Vu
Manh Vu

Reputation: 151

Thank you Ray Nicholus

It works for me.

{
  "formAttributes": {
    "action": "https://**.s3.ap-southeast-1.amazonaws.com",
    "method": "POST",
    "enctype": "multipart/form-data"
  },
  "formInputs": {
    "acl": "public-read",
    "key": "users/2/images/drops-of-water-578897_640.jpg",
    "X-Amz-Credential": "**",
    "X-Amz-Algorithm": "AWS4-HMAC-SHA256",
    "X-Amz-Date": "**",
    "Policy": "**",
    "X-Amz-Signature": "**"
  }
}
function uploadFile(event) {
  event.preventDefault();

  getSignedPost().then(() => {
    const fileEl = document.getElementById('id-file');
    const file = fileEl.files[0];

    const formData = new FormData();
    Object.keys(uploadCredentials.formInputs).forEach((key) => {
      formData.append(key, uploadCredentials.formInputs[key]);
    });

    // update key to file name
    const key = `users/2/images/${file.name}`;
    formData.set('key', key);
    uploadCredentials.formInputs.key = key;

    // update show data on page
    const el = document.getElementById('id-upload-info');
    el.innerText = JSON.stringify(uploadCredentials, null, 2);

    // IMPORTANCE: https://stackoverflow.com/a/15235866
    // AWS ignores all fields in the request after the file field, so all other fields must appear before the file.
    formData.append('file', file);

    fetch(uploadCredentials.formAttributes.action, {
      method: uploadCredentials.formAttributes.method,
      // headers: {
      //   'Content-Type': 'multipart/form-data',
      // },
      body: formData,
    })
      .then((res) => {
        if (res.status === 204) {
          console.log('Successfully uploaded file');
          console.log('-- 204 - no content');

          return `Successfully uploaded file: ${key}`;
        }

        if (res.ok) {
          return res.json();
        } else {
          return res.text();
        }
      })
      .then((res) => {
        alert(JSON.stringify(res, null, 2));
      })
      .catch((err) => {
        alert(err.message || err);
      });
  });
}

Upvotes: 0

Ray Nicholus
Ray Nicholus

Reputation: 19890

It kind of looks like your file form field is appearing first in the request. I can't tell for sure since you have not included the entire request payload in your answer, but it looks like this is appearing just above the "key" field. AWS ignores all fields in the request after the file field, so all other fields must appear before the file.

Upvotes: 75

Related Questions