Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 42 ยท Building Real APIs

File Uploads with Multer

Accept file uploads in NestJS with FileInterceptor and Multer, validate size and type with ParseFilePipe, choose disk or memory storage, and stream downloads with StreamableFile.

Sooner or later an API has to accept a file: an avatar, a PDF invoice, a CSV import. Files do not travel as JSON. Browsers send them as multipart/form-data, a body made of several parts, each with its own headers and bytes. Nest does not parse that format itself. On the default Express platform it uses Multer, a well-known middleware, and wraps it in interceptors so you can write handlers that look like the rest of your controllers.

This lesson shows how to receive one or many files, how to validate them (size and real type), when to keep files in memory and when on disk, how to send a file back with StreamableFile, and how to fix the dreaded "PayloadTooLarge" error. The Nest code is read-only. The runnable stand-ins are real: a loopback HTTP server that reads multipart bodies with Node's built-in Request.formData(), so you can watch uploads, validation and downloads work. Only the Nest and Multer wrappers are replaced by a few lines of hand-written code.

You need the @types/multer package for the Express.Multer.File type, because Nest does not bundle Multer's types. On the Fastify platform, Multer does not apply: you would use @fastify/multipart instead.

Receiving one file

A route that accepts a single file looks like this:

TypeScript
import { Controller, Post, UseInterceptors, UploadedFile, Body } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';

@Controller('avatars')
export class AvatarsController {
  @Post()
  @UseInterceptors(FileInterceptor('avatar'))
  upload(
    @UploadedFile() file: Express.Multer.File,
    @Body() body: { userId: string },
  ) {
    return { name: file.originalname, size: file.size, userId: body.userId };
  }
}

FileInterceptor('avatar') is a normal interceptor. The string is the field name in the form, so the client must send avatar=<file>. Multer runs before your handler, parses the multipart body, and the @UploadedFile() decorator hands you the result. Any text fields in the same form arrive in @Body(), still as strings, so validate them with a pipe.

A client sends it like this (the -F flag makes curl use multipart):

Terminal
curl -F "[email protected]" -F "userId=42" http://localhost:3000/avatars

Many files

There are three interceptors, depending on the shape of the form:

Interceptor Form fields Handler decorator
FileInterceptor('f') one file in field f @UploadedFile()
FilesInterceptor('f', 5) up to 5 files in the same field f @UploadedFiles()
FileFieldsInterceptor([...]) files in several named fields @UploadedFiles() (an object)
TypeScript
@Post('gallery')
@UseInterceptors(FileFieldsInterceptor([
  { name: 'cover', maxCount: 1 },
  { name: 'photos', maxCount: 8 },
]))
gallery(
  @UploadedFiles() files: { cover?: Express.Multer.File[]; photos?: Express.Multer.File[] },
) {
  return { cover: files.cover?.[0]?.originalname, photos: files.photos?.length ?? 0 };
}

The count in the interceptor is a safety limit: a ninth photo makes Multer throw, and Nest turns it into a 400 Bad Request.

Memory or disk storage

Multer needs to put the bytes somewhere while it reads them. You choose with the storage option:

TypeScript
import { diskStorage } from 'multer';
import { extname } from 'node:path';
import { randomUUID } from 'node:crypto';

FileInterceptor('avatar', {
  storage: diskStorage({
    destination: './uploads',
    filename: (req, file, cb) => cb(null, randomUUID() + extname(file.originalname)),
  }),
});
  • Memory storage (the default when you pass no options and no dest) keeps the whole file in a Buffer at file.buffer. It is simple and ideal when you forward the bytes on, for example to object storage. The cost is RAM: ten parallel 50 MB uploads use 500 MB.
  • Disk storage streams the bytes to a file and gives you file.path. Memory use stays low, but you must clean up files you no longer need and think about where they live.

Notice the generated file name. Never trust file.originalname as a path: a client can send ../../etc/cron.d/x. Generate your own name (a UUID plus a vetted extension), and store the original name in the database if you need to show it. On a server with several instances, local disk is not shared, so production systems usually push files to object storage such as S3 and keep only the key in the database.

Validating files

An upload endpoint is an open door, so check every file. Set limits in Multer's options and add validators with ParseFilePipe:

TypeScript
import {
  ParseFilePipe,
  MaxFileSizeValidator,
  FileTypeValidator,
} from '@nestjs/common';

@Post()
@UseInterceptors(FileInterceptor('avatar', { limits: { fileSize: 2 * 1024 * 1024 } }))
upload(
  @UploadedFile(
    new ParseFilePipe({
      validators: [
        new MaxFileSizeValidator({ maxSize: 2 * 1024 * 1024 }),
        new FileTypeValidator({ fileType: /^image\/(png|jpeg)$/ }),
      ],
      fileIsRequired: true,
    }),
  )
  file: Express.Multer.File,
) { /* ... */ }

Notice the two layers. The Multer limits.fileSize stops reading as soon as a file grows too big, so a 5 GB upload does not fill your disk before a validator sees it. MaxFileSizeValidator then checks file.size and gives a clear 400 message. FileTypeValidator checks the file's type, and here you must be careful.

The type that a client declares (Content-Type: image/png) is only a claim. A script can label an executable as a PNG. Recent Nest versions make FileTypeValidator inspect the file's leading bytes ("magic numbers") for known formats, but you should still read the docs for the version you run. For anything security-sensitive, check the bytes yourself or re-encode images on the server, serve uploads from a separate domain or bucket, and never run or include an uploaded file.

Other useful rules: an allow-list of extensions, a count limit per user, antivirus scanning for shared documents, and rejecting empty files.

Sending files back

Returning a file from a handler with @Res() works, but it switches off Nest's standard response handling (interceptors that map the response, for example). StreamableFile keeps you inside the framework:

TypeScript
import { StreamableFile, Header } from '@nestjs/common';
import { createReadStream } from 'node:fs';
import { join } from 'node:path';

@Get('report.pdf')
@Header('Content-Type', 'application/pdf')
@Header('Content-Disposition', 'attachment; filename="report.pdf"')
download(): StreamableFile {
  return new StreamableFile(createReadStream(join(process.cwd(), 'files/report.pdf')));
}

The file is streamed, not loaded into memory, so a 2 GB download costs little RAM. You can also pass the headers through the constructor options (type, disposition, length). Content-Disposition: attachment makes browsers download; inline shows the file in the tab if the browser can render it.

Body size limits and PayloadTooLarge

Two different limits cause confusion:

  1. Multer's limits (fileSize, files, fields) apply to multipart uploads. Exceeding them gives a 4xx error from the interceptor.
  2. The body parser limit applies to JSON and URL-encoded bodies. By default Express accepts about 100 KB of JSON. Larger bodies fail with PayloadTooLargeError: request entity too large (HTTP 413). This is the error people meet when they send a base64 image inside JSON.

Raise the JSON limit deliberately in main.ts when you create the app with bodyParser: false, or use the Express adapter's own parser:

TypeScript
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';

const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.useBodyParser('json', { limit: '5mb' });

Prefer multipart for files and keep the JSON limit small: a big JSON limit makes every endpoint an easier target. A reverse proxy has its own cap too (nginx's client_max_body_size defaults to 1 MB), and it answers 413 before Nest ever sees the request.

Stand-in: a real upload server with validation

This stand-in starts a real HTTP server on the loopback address and uploads real multipart data with fetch and FormData. A small uploadHandler plays the part of FileInterceptor plus ParseFilePipe: it parses the body with Request.formData(), then runs a size validator and a type validator that looks at the first bytes of the file. It is not Multer, but the validation order and error shape are the same idea.

Node.js Upload, validate size and real type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The third upload is rejected by size before its type is inspected, and the "PNG" that is really a shell script is rejected because its bytes do not match: the label the client sent is ignored. With real Nest, ParseFilePipe returns a standard 400 body in the same spirit.

Stand-in: streaming a download

A download should stream. This stand-in serves a generated file through pipeline, with the headers that @Header and StreamableFile would set, and reads it back with fetch.

Node.js Streaming a file response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Readable.from() stands in for createReadStream(). Because the body is a stream, the server can start sending before the whole file exists and a slow client does not make the server hold the full file in memory.

A short checklist

  • Use FileInterceptor and friends; pick memoryStorage only for small files you forward right away.
  • Set Multer limits and add ParseFilePipe validators.
  • Never trust the client's file name or Content-Type; generate your own name and check the bytes.
  • Stream downloads with StreamableFile.
  • Keep JSON limits small, and mind proxy limits such as nginx's client_max_body_size.
  • In production, store uploads in object storage, not on an instance's disk.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the string in FileInterceptor('avatar') mean?

    It is the multipart field name. The client must send the file in a field called avatar, and @UploadedFile() then returns it.
  2. 2. Which storage option keeps the whole uploaded file in RAM?

    Memory storage is simple but uses RAM per concurrent upload. Disk storage streams to a file and gives you file.path.
  3. 3. A client uploads a script and sets Content-Type to image/png. Why is checking file.mimetype alone not enough?

    Any client can claim any type. Inspect magic numbers, re-encode images, and never execute uploaded files.
  4. 4. Large JSON bodies fail with 'PayloadTooLargeError'. What is the best long-term fix for sending files?

    Base64 in JSON inflates the data by about a third and forces a large global limit. Multipart uploads are made for files.
  5. 5. Why return a StreamableFile instead of reading a big file into a Buffer?

    StreamableFile pipes a stream to the response, unlike @Res() it keeps interceptors and other Nest response handling working.

Summary

  • Files arrive as multipart/form-data; on Express, Nest uses Multer through FileInterceptor, FilesInterceptor and FileFieldsInterceptor.
  • @UploadedFile() and @UploadedFiles() give you the parsed files; text fields come in @Body() as strings.
  • Memory storage is easy but costs RAM; disk storage streams to a path. Generate your own file names and prefer object storage in production.
  • Combine Multer limits with ParseFilePipe validators (MaxFileSizeValidator, FileTypeValidator), and never trust a client-declared type.
  • StreamableFile streams downloads without leaving Nest's response pipeline.
  • PayloadTooLarge (413) usually comes from the JSON body limit or a proxy limit; use multipart rather than a huge JSON limit.

Next, call other services from your API in Calling External APIs with HttpModule.