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.
JavaScript
x
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.
JavaScript
fetch(api, { method: 'POST', body, headers, mode: 'cors' });
But when I use axios, the request looks like this, and my PHP server could get the files correctly:
JavaScript
axios.post(api, body, { headers });
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:
JavaScript
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/