Fastify Multipart Streaming File Upload

Accept streaming multipart uploads in Fastify with per-file size limits, MIME allowlists, and disk writes that never buffer whole files.

JavascriptNodeFile Upload

Code

javascriptsnippet
29 lines
import fastify from 'fastify';
import multipart from '@fastify/multipart';
import { createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';

const app = fastify({ logger: true });
await app.register(multipart, {
  limits: { fileSize: 25 * 1024 * 1024, files: 3, fields: 10 },
});

const ALLOWED = new Set(['image/png', 'image/jpeg', 'application/pdf']);

app.post('/upload', async (req, reply) => {
  const saved = [];

  for await (const part of req.files()) {
    if (!ALLOWED.has(part.mimetype)) {
      return reply.code(415).send({ error: 'unsupported type', type: part.mimetype });
    }
    if (part.filename === undefined) continue;

    const target = createWriteStream('uploads/' + part.filename);
    await pipeline(part.file, target);
    saved.push({ name: part.filename, bytes: part.file.bytesRead });
  }
  return { saved };
});

await app.listen({ port: 3000 });

How it works

Repetition is confined to for await (const part of req.files()) — the rest of the file is straight-line. await marks each async boundary — nothing fires and forgets. Reach for fastify and what you get is createWriteStream, pipeline — that is the whole API contact area.

Demo state sits in top-level bindings: app, ALLOWED.

The result is a fresh construction, so callers can keep their originals.

Points of care

  • Plan for an install step: fastify and @fastify/multipart are a real dependency, resolved by the package manager.
  • The guard part.filename === undefined short-circuits the flow with an early continue when its condition holds.

Key statements

return reply.code(415).send({ error: 'unsupported type', type: part.mimetype });
const ALLOWED = new Set(['image/png', 'image/jpeg', 'application/pdf']);
await pipeline(part.file, target);

FAQ

Which packages must be installed first?
Yes. The imports resolve to `fastify` and `@fastify/multipart`, which the package manager must provide.