Submission formats

Multipart form data

Use multipart/form-data when uploading files and let the browser generate the boundary required by the request body.

8 minute lesson

~~~

Use multipart/form-data when a form sends files.

<form action="/support" method="post" enctype="multipart/form-data">
  <input name="subject">
  <input name="screenshot" type="file" accept="image/png,image/jpeg">
  <button type="submit">Send request</button>
</form>

The request body contains separate parts. Each part has headers and content. The text field is one part and the selected file is another.

The Content-Type request header includes a generated boundary:

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary...

That boundary tells the server where one part ends and the next begins.

When sending a FormData object with fetch(), do not set the Content-Type header yourself:

await fetch(form.action, {
  method: 'POST',
  body: new FormData(form)
})

The browser adds the correct header and matching boundary. Manually writing multipart/form-data without a boundary creates a body the server may not parse.

Multipart encoding does not make uploads safe. The server still needs total request limits, per-file limits, type checks, generated storage names, and authorization.

Inspect one multipart request in DevTools. Find the ordinary field, the file part, and the boundary in the request header.

Lesson completed