Overview

FormData is a browser-native API used to build multipart/form-data payloads, often for submitting HTML forms or uploading files via JavaScript.

Basic Usage

const form = document.querySelector('form');
const formData = new FormData(form);

fetch('/submit', {
  method: 'POST',
  body: formData, // auto Content-Type
});

Manual Construction

const formData = new FormData();
formData.append('name', 'Merrick');
formData.append('file', fileInput.files[0]);

Common Methods

Method Description
.append(key, value) Add a new field
.get(key) Get the first value for a field
.getAll(key) Get all values for a field
.set(key, value) Overwrite existing value
.delete(key) Remove a field
.has(key) Check if field exists
.entries() Returns an iterator over [key, value] pairs

Iteration

for (const [key, value] of formData) {
  console.log(key, value);
}

Or:

console.log([...formData.entries()]);

File Upload

<form id="uploadForm">
  <input type="file" name="avatar">
</form>
const form = document.getElementById('uploadForm');
const formData = new FormData(form);

fetch('/upload', {
  method: 'POST',
  body: formData,
});