PREP WITH PROOF
Menu
APIS / PRACTICAL GUIDE

Multipart Form-Data Boundary Errors: Debug File Uploads

Fix multipart/form-data boundary errors, FormData headers and missing upload fields. Includes a Node.js lab with four real local HTTP requests.

THE QUICK ANSWER

A multipart/form-data upload needs a boundary parameter that matches the delimiters in its encoded body. When fetch sends FormData, let the client generate Content-Type. Then verify field names, repeated values, raw file bytes and parser limits separately.

The header and body must describe the same multipart message

A multipart upload has two related pieces: an outer Content-Type header and an encoded body containing separate parts. The boundary parameter tells the receiver which delimiter identifies those parts. If an HTTP wrapper replaces the header but leaves the generated body untouched, the receiver can no longer reliably interpret the message. Looking only at a file picker or a successful network connection misses that mismatch.

Use a harmless development fixture to inspect the request. Record its URL and method, the complete outer Content-Type including boundary, the field names expected by the endpoint, and the server’s parsing result. Inspect authentication, routing and request-size failures separately. A response status alone is not a reliable boundary diagnosis: frameworks and gateways can report malformed uploads using different status codes or error formats.

RFC 7578 defines a boundary parameter and delimiter structure for multipart/form-data. Each form part has Content-Disposition with a name identifying the field; a file part can also supply a filename. The outer boundary value does not include the two delimiter-prefix hyphens. Quotes surrounding a boundary parameter are header syntax, not extra characters to insert into every body delimiter.

The following small body is illustrative, with CRLF line endings required where the multipart syntax calls for them. It contains a text field, not a complete file-upload application. The boundary value ExampleBoundary is deliberately readable for explanation; normal clients should generate their own suitable delimiter rather than reusing this example in arbitrary file content.

Content-Type: multipart/form-data; boundary=ExampleBoundary

--ExampleBoundary
Content-Disposition: form-data; name="title"

Quarterly report
--ExampleBoundary--

Source: RFC 7578 — multipart/form-data boundaries and parts ↗

When FormData owns encoding, let it set Content-Type

With browser fetch and a FormData body, the usual repair is to omit a manually supplied Content-Type header. The browser generates the multipart encoding and the matching boundary parameter together. Setting the header to only multipart/form-data discards the information the parser needs. Setting a custom boundary while leaving FormData to generate the body creates another mismatch.

Check shared API helpers as well as the upload call. A wrapper may add application/json to every request, stringify a FormData object, or copy headers from an earlier request. Treat the body type as part of the helper’s contract. A JSON request and a multipart request need different serialization paths even when they use the same authentication mechanism.

The browser example below assumes an existing file input, a selected file and an endpoint that accepts the field names shown. It illustrates the request shape; it was not exercised in a browser during this run. Adapt the URL, authorization and CSRF behavior to your application. Keep required authentication headers while allowing FormData to own its encoding header.

When constructing FormData from an HTML form, verify that intended controls have names and are included in submission. When appending values manually, verify the exact names expected by the server. A syntactically valid multipart body can still fail application validation because the endpoint expects upload but the client sends file.

// Browser illustration: adapt input, endpoint and authentication.
const input = document.querySelector('input[type=file]');
if (!input?.files?.[0]) throw new Error('Select a file first');
const body = new FormData();
body.append('title', 'Quarterly report');
body.append('file', input.files[0]);
const response = await fetch('/api/upload', {method: 'POST', body});
if (!response.ok) throw new Error(`Upload failed: ${response.status}`);

Source: MDN — using FormData objects and Content-Type ↗

Use a controlled curl comparison without changing the data contract

curl --form, also written -F, builds multipart form requests. Its file syntax uses an @ prefix in a field value. For ordinary text that might begin with @ or contain curl form syntax, --form-string treats the supplied value literally. These options make a small known-file comparison useful without hand-assembling the wire encoding.

Compare the same field names, endpoint and safe test file used by the application. Do not compare an authenticated browser upload with an unauthenticated curl call and conclude that any difference proves a multipart bug. Cookies, redirects, CSRF requirements, accepted methods and gateway routing can all change the result. Record the relevant request differences before changing the implementation.

If you capture verbose or trace output, use test credentials and synthetic content. Traces can contain authorization values, cookies and the entire uploaded file. Retain only the evidence needed to identify the mismatch and handle it through your normal development logging process. Avoid pasting a real customer document into a public debugging service.

A curl success narrows the investigation but does not prove the browser path works. Likewise, a browser may enforce cross-origin rules that curl does not. Inspect a browser’s network panel when the user-facing failure occurs there, and distinguish a request rejected by the server from a response the browser refuses to expose to JavaScript.

Source: curl manual — form and form-string ↗

Check part semantics after the boundary parses

Repeated fields are allowed and can be meaningful. A form might append tag twice or send multiple files under one field name. Do not collapse entries into an ordinary object before deciding how duplicates should be handled; that conversion can silently lose information. Use the framework’s explicit multi-value accessor when the endpoint contract permits repeated fields, and reject unexpected ambiguity when it does not.

Distinguish the field name from the filename. The name determines where the endpoint finds the value. The filename is supplied metadata and should not be trusted as a server filesystem path. A declared part Content-Type is also a client claim, not evidence that the file is safe or actually matches that format. Apply the application’s content validation and storage policy after parsing.

Keep bytes intact while diagnosing binary files. Converting an entire multipart body to a text string and reconstructing it can corrupt byte sequences, line endings or delimiters. If middleware needs to inspect the request, check whether it consumes the body stream before the upload parser runs. A later parser receiving an empty or incomplete stream is a different defect from a missing boundary.

Inspect limits at each relevant layer: the application parser, the HTTP server and any gateway can have their own request and file limits. Test near the actual configured limits in a controlled environment. Increasing a limit will not repair a mismatched delimiter, and a correct delimiter does not make an oversized upload acceptable.

SymptomCheck firstAvoid assuming
Missing boundary errorOuter Content-Type generated by the final client helperThe file itself is damaged
File field absentExact field name, selected file and body consumptionAny multipart error is a delimiter error
Only one repeated value survivesMulti-value parser and application conversionThe sender omitted the other entries
Small file works, large file failsParser/gateway limits and timeout evidenceA different random boundary will fix capacity

Source: RFC 7578 — multipart/form-data boundaries and parts ↗

Reproduce the header mismatch with four real HTTP requests

The complete Node.js fixture below starts a server bound only to 127.0.0.1 on a randomly assigned port. It sends one generated FormData body with two tag entries and a four-byte binary file. The server uses the built-in Request.formData parser to inspect it. It then replays the same captured bytes with missing, incorrect and correctly quoted boundary parameters.

This isolates the header change from body generation. The first and final requests should parse to the same entries. The two deliberately broken headers should produce the fixture’s 400 response. That response is a choice made by this test server, not a promise about the status another framework will return.

The published fixture passed nine checks with Node.js 24.22.1 across four actual loopback HTTP requests. It verified repeated values, filename, declared type, exact binary bytes, delimiter presence, both invalid headers, quoted-boundary parsing and request count. The server buffers only these small fixtures, with a 64 KiB guard, and every client request has a five-second timeout.

This is not a production upload handler: it does not implement authentication, streaming storage, rate control or a general rejection policy. It does not test a browser, curl, TLS, CORS, proxies, large uploads or parser behavior across frameworks. Run it in a development environment that permits loopback sockets and supports the built-in fetch, FormData, Blob and Request APIs. No external upload destination is contacted.

import http from 'node:http';
import assert from 'node:assert/strict';
import {once} from 'node:events';

// Local fixture only: buffers at most 64 KiB; not a production upload server.
const seen = [];
const server = http.createServer(async (req, res) => {
  try {
    const chunks = []; let size = 0;
    for await (const chunk of req) {
      size += chunk.length;
      if (size > 65536) throw new Error('fixture size limit');
      chunks.push(chunk);
    }
    const body = Buffer.concat(chunks);
    const type = req.headers['content-type'] ?? '';
    seen.push({type, body});
    const form = await new Request('http://localhost/upload', {
      method: 'POST', headers: {'content-type': type}, body
    }).formData();
    const entries = [];
    for (const [name, value] of form) {
      entries.push(typeof value === 'string' ? {name, text: value} : {
        name, filename: value.name, type: value.type,
        bytes: [...new Uint8Array(await value.arrayBuffer())]
      });
    }
    res.writeHead(200, {'content-type': 'application/json'});
    res.end(JSON.stringify(entries));
  } catch {
    res.writeHead(400); res.end('fixture parse failed');
  }
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const url = `http://127.0.0.1:${server.address().port}/upload`;
let checks = 0;
try {
  const data = new FormData();
  data.append('tag', 'first'); data.append('tag', 'second');
  data.append('file', new Blob([new Uint8Array([0, 65, 255, 10])],
                              {type: 'application/octet-stream'}), 'sample.bin');
  let r = await fetch(url, {method: 'POST', body: data,
                           signal: AbortSignal.timeout(5000)});
  assert.equal(r.status, 200); checks++;
  const entries = await r.json();
  assert.deepEqual(entries.filter(x => x.name === 'tag').map(x => x.text),
                   ['first', 'second']); checks++;
  assert.deepEqual(entries.find(x => x.name === 'file'), {
    name: 'file', filename: 'sample.bin', type: 'application/octet-stream',
    bytes: [0, 65, 255, 10]
  }); checks++;
  const original = seen[0];
  const boundary = original.type.match(/boundary=(.+)$/)[1];
  assert(original.body.includes(Buffer.from('--' + boundary))); checks++;
  // Same bytes: isolate Content-Type boundary changes from body generation.
  for (const type of ['multipart/form-data',
                      'multipart/form-data; boundary=definitely-wrong']) {
    r = await fetch(url, {method: 'POST', body: original.body,
      headers: {'content-type': type}, signal: AbortSignal.timeout(5000)});
    assert.equal(r.status, 400); checks++;
    await r.text();
  }
  r = await fetch(url, {method: 'POST', body: original.body,
    headers: {'content-type': `multipart/form-data; boundary="${boundary}"`},
    signal: AbortSignal.timeout(5000)});
  assert.equal(r.status, 200); checks++;
  assert.deepEqual(await r.json(), entries); checks++;
  assert.equal(seen.length, 4); checks++;
  console.log(`${checks} checks passed; four real HTTP requests on loopback`);
} finally {
  server.closeAllConnections();
  await new Promise(resolve => server.close(resolve));
}

Verify the final request, then test the application outcome

After a repair, inspect the request that actually reaches the parser. Confirm the effective outer Content-Type, parsed field names, duplicate handling and a byte-for-byte check of a harmless file. Test the failing upload path through the same wrapper that previously added the wrong header; a separate direct-fetch snippet can bypass the defect without fixing it.

Then verify the application outcome: expected validation, storage, ownership and response behavior. Include a missing required field and an intentionally invalid input so successful parsing is not mistaken for successful validation. Keep request identifiers and error classifications useful enough to separate transport, parser and business-rule failures.

The reliable approach is to let one component own multipart serialization, preserve the resulting header/body pair, and diagnose the next layer only after that pair parses correctly. A boundary fix should be demonstrated with the same bytes and field contract that exposed the problem, followed by a check of the real upload workflow.

KEEP THESE THREE THINGS

Your next steps

  1. Keep the generated Content-Type and encoded multipart body together.
  2. Let FormData own its boundary header instead of applying a JSON default.
  3. Separate parser success from field validation, byte preservation and storage.
  4. The local fixture isolates header mismatches without uploading to an external service.

Sources & official resources

Linked resources checked on 2026-10-30. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →