Multipart Form-Data Body Builder
Build multipart/form-data request bodies with custom boundaries, text fields and binary file parts without a browser.
Code
const encoder = new TextEncoder();
export interface MultipartFile {
field: string;
filename: string;
contentType: string;
data: Uint8Array;
}
export interface MultipartBody {
body: Uint8Array;
boundary: string;
contentType: string;
}
export class MultipartFormDataBuilder {
private readonly boundary: string;
private readonly chunks: Uint8Array[] = [];
constructor(boundary?: string) {
this.boundary = boundary ?? "----MultipartBoundary"
+ Math.random().toString(36).slice(2)
+ Date.now().toString(36);
if (this.boundary.length < 1 || this.boundary.length > 70) {
throw new RangeError("boundary length must be between 1 and 70");
}
if (/[\r\n"]/.test(this.boundary)) {
throw new TypeError("boundary must not contain quotes or newlines");
}
}
field(name: string, value: string): this {
this.chunks.push(encoder.encode(
"--" + this.boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"" + escapeName(name) + "\"\r\n\r\n"
+ value + "\r\n",
));
return this;
}
file(file: MultipartFile): this {
if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+*-]+$/i.test(file.contentType)) {
throw new TypeError("invalid file contentType");
}
this.chunks.push(encoder.encode(
"--" + this.boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"" + escapeName(file.field)
+ "\"; filename=\"" + escapeName(file.filename) + "\"\r\n"
+ "Content-Type: " + file.contentType + "\r\n\r\n",
));
this.chunks.push(file.data);
this.chunks.push(encoder.encode("\r\n"));
return this;
}
build(): MultipartBody {
const closing = encoder.encode("--" + this.boundary + "--\r\n");
const length = this.chunks.reduce((total, chunk) => total + chunk.length, closing.length);
const body = new Uint8Array(length);
let offset = 0;
for (const chunk of this.chunks) {
body.set(chunk, offset);
offset += chunk.length;
}
body.set(closing, offset);
return {
body,
boundary: this.boundary,
contentType: "multipart/form-data; boundary=" + this.boundary,
};
}
}
function escapeName(value: string): string {
return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/[\r\n]/g, " ");
}What the code does
Multipart Form-Data Body Builder is built around the class MultipartFormDataBuilder and the function escapeName.
Repetition is confined to for (const chunk of this.chunks) — the rest of the file is straight-line. RangeError and TypeError is the guard’s signal — thrown at the branch, before any partial work happens.
The result comes back as an object carrying body, boundary.
What to watch for
- The guard
this.boundary.length < 1 || this.boundary.length > 70short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The surface worth importing is MultipartFormDataBuilder; the helpers around it are private to the snippet.
The call returns body, boundary — destructure what you need at the call site.
Statements that matter
const length = this.chunks.reduce((total, chunk) => total + chunk.length, closing.length);
return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/[\r\n]/g, " ");
throw new TypeError("boundary must not contain quotes or newlines");
Interactive Tools for This Topic
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- Does `MultipartFormDataBuilder` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- How does the code behave when input is bad?
- `RangeError` and `TypeError` is raised at the guard (`this.boundary.length < 1 || this.boundary.length > 70`), so invalid state never reaches the main logic.
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `escapeName` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.