Skip to content
Advertisement

Uploading file, axios works but fetch API doesn’t, what did I do wrong?

I’m using fetch API to communicate with the server, then I realize when I use fetch API to upload file, the post request looks weird and my PHP server couldn’t get the file by $_FILES correctly.

Here’s my basic setup, the file and fileName are pre-populated.

const api = 'xxxx/api/file';
const body = new FormData();
body.append('files[]', file, fileName);
body.append('bid', 529);

const headers = { 
  'Content-Type': 'multipart/form-data', 
  'Authorization': 'Token xxxxxx'
};

While I’m using fetch API, the post request looks like this, any my PHP server couldn’t get the post data.

fetch(api, { method: 'POST', body, headers, mode: 'cors' });

enter image description here


But when I use axios, the request looks like this, and my PHP server could get the files correctly:

axios.post(api, body, { headers });

enter image description here


So what is going on? Did axios do something different?

And is there a way to achieve this without using axios?

Advertisement

Answer

Try the fetch API without the content-Type key:

const api = 'xxxx/api/file';
const body = new FormData();
body.append('files[]', file, fileName);
body.append('bid', 529);

const headers = { 
  'Authorization': 'Token xxxxxx'
};

delete headers.headers['Content-Type'];

fetch(api, { method: 'POST', body, headers, mode: 'cors' });

Source: https://muffinman.io/blog/uploading-files-using-fetch-multipart-form-data/

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement