Course contentsShow
← JavaScript
Lesson 2286 of 2,72347. Networking PrimitivesFree lesson

FormData for File Uploads

Constructing multipart/form-data requests using FormData for form submissions and file uploads.

FormData for File Uploads

You'll learn how to construct multipart/form-data requests using FormData to upload files and submit form data through Fetch.

What is FormData?

FormData is a built-in JavaScript object that makes it incredibly easy to build multipart/form-data requests—the format browsers use when submitting forms with files. Think of it as a helper that automatically handles the complex encoding needed to mix regular text fields with binary file data in a single HTTP request.

Creating and Using FormData

You can create a FormData instance and append fields to it, just like building a form programmatically:

const formData = new FormData();
formData.append('username', 'alice123');
formData.append('bio', 'Web developer');

Adding Files

To upload files, append a File or Blob object. This is typically retrieved from an <input type="file"> element:

const fileInput = document.querySelector('#avatar');
const file = fileInput.files[0];

const formData = new FormData();
formData.append('avatar', file);
formData.append('description', 'My profile picture');

Sending with Fetch

When you pass FormData as the request body, Fetch automatically sets the correct Content-Type header (including the multipart boundary):

fetch('/upload', {
  method: 'POST',
  body: formData
  // Don't set Content-Type header manually!
})
  .then(response => response.json())
  .then(data => console.log('Upload successful:', data));

Why It's Useful

Without FormData, manually constructing multipart requests is painful—you'd need to handle binary encoding, boundaries, and headers yourself. FormData does all that work behind the scenes, making file uploads as simple as regular form submissions.

Key Takeaway: FormData simplifies multipart/form-data requests by letting you append both text and file data, then automatically handling the complex encoding when used as a Fetch request body.