zyyyzzz
zyyyzzz

Reputation: 230

Append FormData to axios data

So I want to append formData multiple files to axios post. What I have:

const formData = new FormData();
  for (const i of Object.keys(item_images)) {
       formData.append('item_images[]', item_images[i]);
  }

http({
     method: el.method,
     url: el.action,
     data: {
             name: name,
             files: formData
           }
    })

But this doesn't work and it returns me empty request of files:

  'files' => 
  array (
  ),

But when I change axios to this it works and returns files:

http({
     method: el.method,
     url: el.action,
     data: formData
    })

But I need to make first one to work. What could be wrong?

Upvotes: 2

Views: 668

Answers (2)

turkishpeter
turkishpeter

Reputation: 54

You probably need to append all the data in your method one by one. And then in the axios call, you have to specify a content-type header like this:

axios.post('call/some/api', data, {
  headers: {
    'Content-Type': 'multipart/form-data',
  },
});

Hope it works!

Upvotes: 0

Quentin
Quentin

Reputation: 943185

Form Data objects do not support serialization to JSON.

You need to pick multipart or JSON as you data format and stick with it.

If you go with JSON then you'll need to convert your files to a data format you can encode in JSON (e.g. Base 64 strings) and then convert them back on the server.

If you go with multipart, then you'll need to append all your data, not just the files, to the formData object.

formData.append('name', name);

Upvotes: 1

Related Questions