🔄 Ajax: Fix a Multipart Boundary Breaking on a Long File Name
When you build a multipart/form-data request body manually instead of letting the browser’s native FormData object handle it, every file part needs its filename field properly quoted and escaped inside the Content-Disposition header — and a file name containing an unescaped double quote, or one long enough combined with other metadata to push a line past what some older multipart parsers on the server side tolerate, can corrupt the boundary detection for that part, causing the server’s multipart parser to either truncate the file name or, in the worst case, misread where that part ends and the next one begins.
🔎 The Problem
Hand-built multipart body for a file named: My "Vacation" Photo (Final).jpg
------WebKitFormBoundary7MA4YWxk
Content-Disposition: form-data; name="file"; filename="My "Vacation" Photo (Final).jpg"
Content-Type: image/jpeg
<binary data>
------WebKitFormBoundary7MA4YWxk--
^ the unescaped quotes inside the filename itself close the
filename="..." attribute early - a strict server-side multipart
parser reads "My " as the entire filename and then chokes on the
unexpected 'Vacation" Photo (Final).jpg"' text that follows
✅ Fix: Let the Browser’s FormData Build the Body, Don’t Hand-Roll It
- Use the native
FormDataAPI (const fd = new FormData(); fd.append('file', fileObject)) and let the browser serialize the multipart body and set theContent-Typeboundary header itself — it already correctly percent-encodes or escapes problem characters in the filename per the spec, which a hand-built string template almost never gets fully right. - If the request genuinely has to be built manually (a non-browser environment, a specific legacy server quirk), escape at minimum double quotes and backslashes in the filename per RFC 7578 (
\"and\\) before inserting it into theContent-Dispositionheader. - Consider renaming or sanitizing exotic filenames client-side before upload when the receiving server is known to use an older or stricter multipart parser, since even a technically spec-correct escaped filename can still trip parsers that were never tested against anything beyond simple ASCII names.
🚨 Why This Is Dangerous
- A broken multipart boundary doesn’t always fail the whole request outright — some lenient parsers will silently misattribute bytes between parts, meaning a corrupted upload can succeed with a 200 response while quietly storing the wrong file name, a truncated file, or data bleeding from one form field into another.
Multipart boundaries are just string matching under the hood — anything in a filename that can look like the boundary’s own syntax is something you have to escape yourself the moment you stop letting the browser build the request for you.





