Skip to content

Fix uploading files using fetch and multipart/form-data

New Course Coming Soon:

Get Really Good at Git

I had a form that accepted a file and some fields and I wanted to send this data to the server through the Fetch API, like this (React code):

<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>

I had a problem. The files data was not actually sent to the server.

The solution was this: you must NOT set the headers.

I did set the multipart/form-data header as that’s what you do with files upload, but apparently that’s what is breaking the file upload through fetch.

Remove the headers from the fetch request and things should be working.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: