4

I am trying to upload files to S3, files are successfully uploaded and but when downloaded it contains WebKitFormBoundary

------WebKitFormBoundaryrTBzWaHQntWAtZLX
Content-Disposition: form-data; name="file"

hello world
------WebKitFormBoundaryrTBzWaHQntWAtZLX--

Upload using axios

const formData = new FormData();
formData.append('file', this.file);

this.axios.put(this.formUrl,
                formData,
                {
                    headers: {
                        // 'Content-Type': `multipart/form-data`,
                        'Content-Type' : 'application/octet-stream',
                    },
                })
                .then((res) => {

console.log(res) }).catch((e) => { console.error(e) });

How do I remove boundary

Rafee
  • 3,975
  • 8
  • 58
  • 88

1 Answers1

23

I faced the same issue. But the solution is simple. Here is my code I used to upload the file

axios({
    method: "PUT",
    url: url,
    data: fileToUpload,  // NOTE - this is the file not the FormData Object
    headers: { 
        "Content-Type": "multipart/form-data" }
    })
    .then(res => {
        this.setState({
            uploadSuccess: "File upload successfull",
                error: undefined
            });
     })
    .catch(err => {
       console.log(err) 
    });

What really happens is when you attach the file to FormData the FormData get serialized and that serialized data is stored in S3. That's why the file become corrupted.

In the solution we don't wrap the file inside a FormData object. What we do is we directly add the file to data attribute. So nothing other than the file itself get serialized and stored in S3.

Hope this answer would help

Shashith Darshana
  • 2,715
  • 1
  • 25
  • 27
  • For someone trying to solve it using pure ajax you need to have "false" for "processData" flag in the request. – Shashith Darshana Sep 03 '19 at 09:35
  • Thanks a lot! You saved my day! For big files though I would like to do multipart with chunks so I can see in frontend the progress of upload. Any Idea how I could achieve this? I imagine, I could remove the multipart noise from file after upload with a trigger in lambda. But that seems to be a lot of work. – oFace May 07 '21 at 15:54