Skip to content

How to use the FormData object

New Course Coming Soon:

Get Really Good at Git

Find out what is a FormData object and how to use it

The FormData object is used to store form input fields values.

It’s especially useful when you need to send files to the server.

It’s probably the only time you’ll actually need it.

Here is one example of using FormData to send the content of a file using fetch.

We have an input field:

<input type="file" id="fileUpload" />

We attach a change event handler on it:

document.querySelector('#fileUpload').addEventListener('change', (event) => {
  handleImageUpload(event)
})

and we manage the bulk of our logic in the handleImageUpload() function:

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

In this example we POST to the /saveImage endpoint.

You could send more data too by appending it to the formData object.

In the server-side, to access the file data you must parse the request as a multipart form.

See for example how to upload files in a Next.js form

The FormData object you create has many useful methods:

The FormData object is part of the XMLHttpRequest 2 spec.

It’s available in all the modern browsers and it’s most often used when sending images through fetch.

See how to handle images uploaded server-side

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 Summer 2024. Join the waiting list!
→ Read my DOM Tutorial on The Valley of Code
→ Read my Browser Events Tutorial on The Valley of Code
→ Read my Browser APIs Tutorials on The Valley of Code

Here is how can I help you: