FormData
FormData represents a set of form fields — name/value pairs that can
be sent as a multipart/form-data request body. It is the standard way
to upload files or mixed content through fetch().
new FormData()creates an empty form.form.append(name, value)andform.set(name, value)add or overwrite fields. Values can be strings orBlobs (includingFiles, with an optional filename as the third argument).form.get(name)returns the first value for a field;form.getAll(name)returns all of them.form.has(name)andform.delete(name)test and remove fields.- The form is iterable (
entries(),keys(),values(),forEach()).
Usage#
Building and sending a form:
const form = new FormData();
form.append("username", "alice");
form.append("tags", "admin");
form.append("tags", "beta");
const avatar = new Blob([bytes], { type: "image/png" });
form.append("avatar", avatar, "alice.png");
const response = await fetch("https://example.com/profile", {
method: "POST",
body: form, // sent as multipart/form-data
});
Inspecting a form:
console.log(form.get("username")); // "alice"
console.log(form.getAll("tags")); // ["admin", "beta"]
for (const [name, value] of form.entries()) {
console.log(name, typeof value === "string" ? value : value.size);
}