yukashima huksay
yukashima huksay

Reputation: 6248

can't send multipart with fetch but axios works fine

Here is my code:

function uploadImage(payload) {
  return fetch('/api/storage/upload/image/', {
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/form-data',
      Accept: 'application/json',
      Authorization: 'Bearer <token>',
    },
    body: payload,
  });
}
function uploadImage2(payload) {
  return axios.post('/api/storage/upload/image/', payload, {
    headers: {
      'Content-Type': 'multipart/form-data',
      Accept: 'application/json',
      Authorization: 'Bearer <token>',
    },
  });
}
function test(file, meta_data) {
  var formBody = new FormData();
  formBody.set('image', file);
  formBody.set('meta_data', meta_data);

  uploadImage(formBody);
  // doesn't work
  uploadImage2(formBody);
  // works
}

Can someone please explain to me how I'm supposed to send multipart requests with fetch?

The error I get with this code is: 400 bad request, file and meta_data are null.

Upvotes: 3

Views: 888

Answers (2)

The CodePunker
The CodePunker

Reputation: 195

Do not use this header: 'Content-Type': 'multipart/form-data'.

Remove the header and it should work.

Explanation:

When using fetch with the 'Content-Type': 'multipart/form-data' you also have to set the boundary (the separator between the fields that are being sent in the request).

Without the boundary, the server receiving the request won't know where a field starts and where it ends.

You could set the boundary yourself, but it's better to let the browser do that automatically by removing the 'Content-Type' header altogether.

Here's some more insight: Uploading files using 'fetch' and 'FormData'

Upvotes: 6

yukashima huksay
yukashima huksay

Reputation: 6248

Here is what worked for me:

function uploadImage(payload) {
  return fetch('/api/storage/upload/image/', {
    method: 'POST',
    headers: {
      Authorization: 'Bearer <token>',
    },
    body: payload,
  });
}

By comparing the cURL requests sent by the browser I discovered that in the axios request has this:

"Content-Type": "multipart/form-data; boundary=---------------------------19679527153991285751414616421",

So I figured that when you manually specify the content type, fetch respects that and doesn't touch anything while still does it's thing the way it wants:-/ so you just shouldn't specify it, fetch will know itself since you are using formData()

Upvotes: 0

Related Questions