Design a multipart/form-data upload API: handle boundaries, limits, and file validation
multipart/form-data carries text fields and files as separate parts in one HTTP request body. For a file-upload API, the client must generate a valid body with its boundary, while the server parses each part as a stream and enforces total and per-file limits and file checks. The format itself does not provide resumable transfer, integrity verification, or malware detection.
multipart/form-data carries text fields and files as separate parts in one HTTP request body. For a file-upload API, the client must generate a valid body with its boundary, while the server parses each part as a stream and enforces total and per-file limits and file checks. The format itself does not provide resumable transfer, integrity verification, or malware detection.
Requirements of the request format
RFC 7578 defines a multipart/form-data body as parts separated by the boundary parameter in Content-Type. Every part needs a Content-Disposition: form-data; name="..." header. A file part may include a filename, but it is not always required. A part may include Content-Type; for a file, use the known media type or application/octet-stream when it is unknown.
When passing browser FormData to fetch, do not set Content-Type yourself. The browser must add the boundary parameter that matches the body. If you set only multipart/form-data manually, the missing boundary can prevent the server parser from separating parts.
const data = new FormData();
data.append("description", "Profile photo");
data.append("file", fileInput.files[0]);
const response = await fetch("/api/uploads", {
method: "POST",
body: data,
// Let the browser set Content-Type with its boundary.
});To send multiple files for one field, send each file as a separate part with the same name. Document whether duplicate field names are preserved as a list or overwritten by one value. If order matters, confirm that the parser preserves part order.
Server receive and validation flow
**Authenticate the request and check upload permission.** For browser APIs using cookie-based sessions, also consider CSRF defenses. `multipart/form-data` does not provide authentication or confidentiality.
**Apply request-wide limits first.** Limit total request bytes, part count, part-header size, text-field size, per-file size, processing time, and concurrent uploads at both the reverse proxy and application. `Content-Length` may be absent or untrusted, so count actual streamed bytes and stop immediately at the limit.
**Parse as a stream with a maintained multipart parser.** Return a clear 4xx response for a missing or malformed boundary or broken headers/closing delimiter. Do not buffer the whole file in memory; enforce limits while writing to temporary storage. Remove temporary files after an intermediate failure or client disconnect.
**Do not trust metadata.** `filename` is user input. Strip path information and generate a safe internal storage name. If the original name is needed, keep it as separately constrained metadata. The client can also choose a part's `Content-Type`, so it is not a substitute for inspecting the file contents.
**Check allowed formats and actual content.** Define an extension allowlist for the business need and inspect content with signatures or a safe format-specific parser. Do not rely on a MIME header alone. Where appropriate, scan or sanitize the file in an isolated environment before publishing it.
**Publish only after validation and return a result.** After size, format, authorization, and scan checks pass, atomically move the temporary file to storage suitable for publication or downstream processing. Ensure failures leave no partial files, and return an upload ID and status for the client.
The boundary is a delimiter inside the body, not the length of the complete HTTP message. Do not confuse multipart boundaries with HTTP message framing. A successful multipart/form-data request also need not mean that file processing or publication is complete; for asynchronous scanning, distinguish receipt from processing completion.
Error handling and operational limits
Define the response when the total request, file size, file count, or account quota is exceeded. Distinguish parse errors from policy rejection and clean up any parts already stored temporarily. Reclaim file handles and storage when the client disconnects or a read timeout expires.
Multipart upload is not a protocol for splitting a large file across requests and resuming later. A browser FormData request is generally one body. If clients need resume after interruption, chunk retries, or progress tracking, design a separate resumable-upload protocol or object-storage session, and verify the assembled object when it completes.
Before deployment
Does the browser-generated `boundary` match what the server parser receives?
Are total request size, per-file size, part count, field size, and processing time limited separately?
Are duplicate field names and multiple files handled by a documented contract?
Are filenames and MIME headers treated as untrusted, with content checks and internal storage names?
Are temporary files and resources cleaned up on errors, timeouts, and disconnects?
Are upload receipt, security scanning, and publication represented as distinct states?
Are resumable-transfer requirements handled by a resumable protocol rather than `multipart/form-data` alone?
Sources
[RFC 7578: Returning Values from Forms: multipart/form-data](https://datatracker.ietf.org/doc/html/rfc7578)
[MDN: Using FormData Objects](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects)
[OWASP: File Upload Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html)