How to Implement Multipart Form Data Parsing
Parse multipart/form-data safely: understand the boundary framing, stream fields and files, enforce limits per part, and avoid buffering whole uploads.
On this page
Introduction
A form with a file input sends its data as multipart/form-data, a format that packs several independent parts into one request body. Each part carries its own headers and body, separated by a boundary token. Parsing it correctly is a small protocol problem: the boundary must be exact, the part headers must be read before the part body, and the whole thing must be streamed because a file part can be large. Handling it as one string split on a delimiter works for tiny forms and fails on real ones.
This tutorial implements multipart parsing for a Node.js upload endpoint. It covers extracting the boundary, reading part headers, streaming file parts with per-part and total limits, protecting against a flood of fields, and testing malformed and hostile input. The examples use a streaming parser, which is the correct approach for anything that accepts files.
Read the boundary and frame the parts
The Content-Type header of the request is multipart/form-data; boundary=––abc123. The boundary token is the delimiter that appears between parts, preceded by two hyphens, and the body ends with the boundary followed by two more hyphens. Extract the boundary and reject the request if it is missing, because without it the body is unparseable. Also reject a boundary that is absurdly long or contains characters outside the permitted set, as a hostile client can use it to confuse a naive parser.
Parts in the body appear as the boundary, a CRLF, a set of part headers, a blank line, the part body, and a CRLF before the next boundary. The final boundary has an extra trailing CRLF sequence. A correct parser scans for the boundary at line starts rather than anywhere in the data, because a file part may legitimately contain the boundary bytes in its content. This line-anchored scanning is the detail that separates a parser that works from one that corrupts binary uploads.
Parse part headers before the body
Each part begins with headers such as Content-Disposition: form-data; name=“field”; filename=“photo.png” and optionally a Content-Type. Read and parse these headers first, then decide what to do with the body. The name identifies the form field; the filename, when present, marks the part as a file upload. Never act on the body until you know the field name, because the action depends on it.
Treat filename as untrusted. It is client-supplied and can contain a path separator, a control character, or a misleading extension. Use it as a display hint and generate your own storage key; sanitize the name before logging or presenting it. Do not derive a filesystem path directly from it, or a crafted name can escape the intended directory.
import { parse } from 'content-type';
function boundaryOf(contentType) {
const parsed = parse(contentType); // { type, parameters }
if (parsed.type !== 'multipart/form-data') return null;
const boundary = parsed.parameters.boundary;
if (typeof boundary !== 'string' || boundary.length > 200) return null;
return boundary;
}
Stream file parts with limits
A file part can be arbitrarily large, so stream its body to its destination rather than buffering it. Apply a per-file cap and a total body cap, both enforced while reading, and count the number of parts so a request with thousands of tiny fields cannot consume unbounded memory in the parser’s part list. When a limit is exceeded, abort the request with 413 and clean up any partial write.
Distinguish fields from files. A field part is usually small and can be read into a string, but cap its size too, because a field can also be huge if the client chooses. Accumulate fields into a bounded structure and reject duplicates where the schema expects one value. For nested field names such as user[address][city], either support a known syntax or reject unknown shapes rather than building an arbitrary object graph from client input.
import Busboy from 'busboy';
function handleMultipart(req, res, { maxFileBytes, maxFieldBytes, maxParts }) {
const busboy = Busboy({ headers: req.headers, limits: {
fileSize: maxFileBytes, fieldSize: maxFieldBytes, files: 50, fields: 50, parts: maxParts,
}});
busboy.on('file', (name, stream) => { stream.resume(); });
busboy.on('field', (name, value) => { /* validate and store */ });
busboy.on('close', () => { if (!res.writableEnded) res.writeHead(201).end('ok'); });
req.pipe(busboy); // streamed, never buffered whole
}
Handle malformed and hostile input
Reject requests with a missing or malformed boundary, a body that ends before a final boundary, or a part header that does not parse. A truncated upload should fail cleanly rather than leaving a half-written file. Validate the overall Content-Length if present and enforce the caps regardless. If the parser cannot make progress, destroy the connection instead of waiting for more data forever.
Guard against resource-based abuse. Cap the number of parts, the size of each field, the size of each file, and the total. Reject an upload whose declared length already exceeds the cap. Log rejected uploads with a reason code so you can tell a misconfigured client from an attack. These limits are not optional for any endpoint that is reachable from the internet.
Test real multipart edge cases
Send a form with one text field and one file and assert both are parsed with the right names. Send a request with no boundary and assert a 400. Send a file part that exceeds the per-file cap and assert 413 and that no partial file remains. Send a body with hundreds of fields and assert the parts limit triggers. Send a file whose content contains the boundary bytes at a non-line position and assert it is preserved intact.
curl -s -o /dev/null -w '%{http_code}\n' -F 'title=report' -F '[email protected]' http://localhost:3000/upload
curl -s -o /dev/null -w '%{http_code}\n' -H 'content-type: multipart/form-data' --data-binary 'x' http://localhost:3000/upload
Common pitfalls
Buffering the whole body, splitting on the boundary anywhere instead of at line starts, trusting the client filename as a path, having no per-file or per-part limit, and letting an unbounded number of fields accumulate are the recurring mistakes. Streaming with a real parser, line-anchored boundary scanning, sanitizing the filename, and explicit limits address them, and the hostile-input tests confirm the guardrails hold.
Conclusion
Multipart parsing is a framing problem plus a streaming problem. Read the boundary from Content-Type, scan for it at line starts, parse part headers before the body, stream file parts with per-file and total caps, and sanitize client-supplied names. Self-check by sending an oversized file and asserting 413 with no leftover file, and by sending a missing boundary and asserting 400. With limits in place, an upload endpoint is robust instead of a memory hazard.
Sources: RFC 7578: Returning Values from Forms: multipart/form-data, MDN: POST method, MDN: Content-Disposition header.
FAQ
- Why do I need the boundary?
- The multipart body has no length prefix per part; the boundary is the delimiter that separates them. Without the exact boundary from Content-Type, the parser cannot tell where one part ends and the next begins, so a missing or wrong boundary must be rejected.
- Should I trust the filename from the client?
- No. The filename is client-controlled and can contain path separators or control characters. Treat it as a display hint only; generate your own storage key and sanitize the name before using it.
Report a problem with this articleOpens a pre-filled issue on GitHub.