Fix uploading files using fetch and multipart/form-data
By Flavio
Published · Updated
Tagged: JavaScript
Fix file uploads with fetch and FormData that never reach the server: do not set the multipart/form-data Content-Type header and let the browser add it.
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.
const res = await fetch('/api/post', {
method: 'POST',
body,
})
Why setting the header breaks the upload
A multipart body is made of parts, one for each field. The parts are separated by a random string called the boundary.
When you pass a FormData object as the body and don’t set a Content-Type, the browser generates the boundary and sets the header for you, including it:
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryAbC123
The body then looks like this:
------WebKitFormBoundaryAbC123
Content-Disposition: form-data; name="title"
Hello
------WebKitFormBoundaryAbC123
Content-Disposition: form-data; name="image"; filename="cat.png"
Content-Type: image/png
...file bytes...
If you set the header yourself, the browser uses your value as it is. The body is still split with a boundary, but the header doesn’t say what the boundary is. The server has no way to find where each part starts and ends.
I tested it with an Express server using multer. Without the header, the file and the fields arrive fine. With 'Content-Type': 'multipart/form-data', multer returns this error:
Multipart: Boundary not found
The same happens with fetch() in Node.js, which has FormData built in since Node 18.
Build the FormData from the form
You don’t need to append every field by hand. Pass the form element to FormData and it picks up all the fields with a name attribute, files included:
form.addEventListener('submit', async (event) => {
event.preventDefault()
const body = new FormData(form)
const res = await fetch('/api/post', {
method: 'POST',
body,
})
})
In React, use new FormData(e.currentTarget) inside the onSubmit handler.
Append the file, not the input
If you append fields yourself, append the File object. A file input has a files list, so take the first item:
const input = document.querySelector('input[type="file"]')
const body = new FormData()
body.append('image', input.files[0])
For an input with multiple, append each file with the same name:
for (const file of input.files) {
body.append('photos', file)
}
On the server, all the files arrive under photos.
If you have a Blob instead of a File, for example an image you made with a canvas, pass a filename as the third argument. Otherwise the server sees the name blob:
body.append('image', blob, 'avatar.png')
Don’t turn FormData into JSON
This sends an empty object:
fetch('/api/post', {
method: 'POST',
body: JSON.stringify(body), // '{}'
headers: { 'Content-Type': 'application/json' },
})
JSON.stringify() doesn’t know how to read a FormData object, and a file can’t go in JSON anyway. Send the FormData as the body directly.
Also, every value that’s not a file becomes a string. body.append('count', 5) arrives as '5', so convert numbers and booleans on the server.
Check the response
fetch() only rejects on network errors. A 400 or 500 response from the server is still a resolved promise, so check res.ok:
const res = await fetch('/api/post', { method: 'POST', body })
if (!res.ok) {
console.error('Upload failed', res.status, await res.text())
}
The server needs a multipart parser
express.json() and express.urlencoded() don’t read multipart bodies. Without a multipart parser, req.body is empty and there’s no file.
In Express you need a library like multer or formidable. Here’s how to handle file uploads in Express.
Upload progress
fetch() doesn’t give you upload progress events. If you want a progress bar, use XMLHttpRequest and listen to xhr.upload.onprogress. The same rule applies there: send the FormData and don’t set the Content-Type header.
Want me to talk about your product? You can sponsor this site.
Related posts about js: