/

Fix Uploading Files Using Fetch and multipart/form-data

Fix Uploading Files Using Fetch and multipart/form-data

In a recent project, I encountered an issue while trying to upload files along with other form fields using the Fetch API in React. The code looked something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<form
encType="multipart/form-data"
action="/api/post"
method="POST"
onSubmit={async (e) => {
e.preventDefault();

if (!title) {
alert('Enter a title');
return;
}
if (!content && !image) {
alert('Enter some text in the post');
return;
}

const body = new FormData();
body.append('image', image);
body.append('title', title);
body.append('content', content);

const res = await fetch('/api/post', {
body,
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
});
}}
>
{/* Form fields */}
</form>

The problem I faced was that the file data was not being sent to the server properly.

After some investigation, I found the solution: do not set the headers.

I had set the multipart/form-data header as it is commonly done for file uploads. However, it turned out that this was causing the file upload to fail when using fetch.

To fix the issue, simply remove the headers option from the fetch request. Once that change is made, the file upload works as expected.

By ensuring that the headers are not set, the Fetch API can handle the file upload seamlessly without any issues.

Tags: file upload, Fetch API, multipart/form-data