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:

<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