AI Workshop: learn to build apps with AI →
File APIs: FormData

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 one
  • delete() removes a key-value pair
  • entries() returns an iterator you can loop over to list the key-value pairs
  • get() returns the value associated with a key (the first one if multiple were appended)
  • getAll() returns all values associated with a key
  • has() — returns true if the key exists
  • keys() returns an iterator you can loop over to list the keys
  • set() 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

Lessons in this unit:

0: Introduction
1: The File object
2: FileList
3: FileReader
4: Blob
5: ▶︎ FormData
6: Accept only images in file input
7: Check if checkbox is checked
8: Reset a form
9: File upload with server handling
10: Drag and drop file upload
11: Validating file size before upload