Content-Type for Multipart Form Data
Set the Content-Type header for multipart/form-data with auto-generated boundary. Covers file uploads, boundary syntax, and part headers.
Form Submissions
Detailed Explanation
Multipart Form Data
multipart/form-data is the Content-Type used for HTML forms that include file uploads or binary data. Each field in the form becomes a separate "part" in the message body, delimited by a boundary string.
The Header Value
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryABC123
The Boundary Parameter
The boundary is a unique string that separates parts in the body. It must:
- Not appear anywhere in the actual content
- Be no longer than 70 characters (per RFC 2046)
- Contain only ASCII characters
Message Body Structure
------WebKitFormBoundaryABC123
Content-Disposition: form-data; name="username"
john_doe
------WebKitFormBoundaryABC123
Content-Disposition: form-data; name="avatar"; filename="photo.jpg"
Content-Type: image/jpeg
[binary file data]
------WebKitFormBoundaryABC123--
Note the final boundary has -- appended to signal the end.
Important Notes
- Browsers auto-generate the boundary: When using
FormDatain JavaScript, the browser sets the Content-Type header automatically. Do not set it manually or the boundary will not match. - Server-to-server: When making requests from backend code, you must set the boundary yourself and ensure it matches the body structure.
fetch() Example
// Browser automatically sets Content-Type with boundary
const formData = new FormData();
formData.append("file", fileInput.files[0]);
formData.append("name", "document.pdf");
fetch("/upload", {
method: "POST",
body: formData // Do NOT set Content-Type manually
});
Use Case
Use this for file uploads, image submissions, and any form that includes binary data. The browser handles boundary generation automatically when using the FormData API.