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.
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.
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();{ 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.