0

Vue2.js + axios, can't append file to form data

axios.post( '/addTrack', this.form.data )

form data object:

        form: {
            data: {
                title : '',
                style : '',
                authors: [
                    {
                        id: '',
                        rightholder: 1,
                        percent: ''
                    }
                ],
                composers: [
                    {
                        id: '',
                        rightholder: 1,
                        percent: ''
                    }
                ],
                right_area: 1,
            },
            errors: {
            }
        },

How to add a file to this request? This doesn't work:

this.form.data.file = e.target.files[0];

console.log shows that form.data.file property is correct File object, but axios send this:

file:{_choosed: true}

Content-Type:application/json

fiter
  • 743
  • 1
  • 12
  • 25
  • You need to encode the file to be transmitted as part of the form. You can [encode it in base64](https://stackoverflow.com/questions/36280818/how-to-convert-file-to-base64-in-javascript), for example, and decode it server-side – salezica Jun 02 '17 at 18:05
  • Have you set any `Content-Type` in the headers? – Umair Sarfraz Jun 02 '17 at 18:06
  • by default Content-Type:application/json – fiter Jun 02 '17 at 19:20

1 Answers1

0

As suggested by Umair, try setting the headers in the optional config parameter for the Axios post method as follows:

axios.post('/addTrack', this.form.data , {
  headers: {
    'Content-Type': 'multipart/form-data'
  }
});
Chris Mills
  • 526
  • 5
  • 8
  • Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0 – fiter Jun 02 '17 at 19:08
  • Ok, get rid of the header config value, then try this: Create your form data like this: `var myForm = document.getElementById('myForm'); var formData = new FormData(myForm);` Then add your file to the form data with the append method: `formData.append(e.target.files[0]);` – Chris Mills Jun 02 '17 at 19:44
  • It works! And there is no sense to append file because it already in myForm variable – fiter Jun 03 '17 at 18:27