Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
The FormData object represents form fields and their values. It is especially useful for sending files to the server and is commonly used with fetch for file uploads.
Example: send a file with FormData and fetch.
HTML:
<input type="file" id="fileUpload" />
Listen for change:
document.querySelector('#fileUpload').addEventListener('change', (event) => {
handleImageUpload(event)
})
Upload logic:
const handleImageUpload = (event) => {
const files = event.target.files
const formData = new FormData()
formData.append('myFile', files[0])
fetch('/saveImage', {
method: 'POST',
body: formData,
})
.then((response) => response.json())
.then((data) => {
console.log(data)
})
.catch((error) => {
console.error(error)
})
}
This POSTs to /saveImage. You can append more fields to the FormData before sending. On the server, parse the request as multipart/form-data to access the file.
See for example how to upload files in a Next.js form
FormData provides these methods:
append()adds a value to the object with the specified key. If the key already exists, the value is added without removing the first onedelete()removes a key-value pairentries()returns an iterator you can loop over to list the key-value pairsget()returns the value associated with a key (the first one if multiple were appended)getAll()returns all values associated with a keyhas()— returns true if the key existskeys()returns an iterator you can loop over to list the keysset()adds a value with the specified key (replacing any existing value for that key)values()returns an iterator you can loop over to list the values
FormData is part of the XMLHttpRequest 2 spec and is supported in modern browsers. It is often used with fetch for file uploads.
See how to handle images uploaded server-side