Fix uploading files using fetch and multipart/form-data
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.
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025