Skip to content
jshacks.dev
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read
Summarize in AI

Node.js has no built-in multipart parser, but its Request class has one. If you build a Request around the incoming stream, formData() gives you the fields and files.

upload-server.jsJavaScript
import { createServer } from 'node:http';
import { Readable } from 'node:stream';

const server = createServer(async (req, res) => {
  const request = new Request('http://localhost/', {
    method: 'POST',
    headers: req.headers,
    body: Readable.toWeb(req),
    duplex: 'half',
  });
  const form = await request.formData();
  const file = form.get('avatar');
  res.end(JSON.stringify({
    user: form.get('user'),
    name: file.name,
    size: file.size,
    text: await file.text(),
  }));
});
await new Promise((resolve) => server.listen(0, resolve));

const body = new FormData();
body.append('user', 'ada');
body.append('avatar', new File(['hello'], 'hello.txt', { type: 'text/plain' }));

const res = await fetch(`http://localhost:${server.address().port}/`, {
  method: 'POST',
  body,
});
console.log(await res.json());

server.close();
Text
{ user: 'ada', name: 'hello.txt', size: 5, text: 'hello' }

formData() reads the whole body into memory before it returns, so this suits small uploads such as avatars. For large files, use a streaming parser like busboy and write each part straight to disk or object storage.

Whatever the parser, set a size limit, check the file type by content rather than by the name the client sent, and never use the client's filename as a path on disk. Needs Node.js 20 or later.

Also inNode.js
Taggednode 24
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.