0Pricing
NestJS Enterprise Backend APIs · 강의

Multer 인터셉터를 사용한 멀티파트 업로드

FileInterceptor와 FilesInterceptor를 연결해 크기 제한이 있는 단일 파일 및 여러 파일 업로드를 처리합니다

Multer 인터셉터를 사용한 멀티파트 업로드은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Multer for Uploads

HTTP file uploads use the multipart/form-data content type, which splits the request body into parts: text fields and binary file payloads separated by a boundary marker.

NestJS does not parse this format on its own. Instead it ships first-class wrappers around Multer, the de-facto Express middleware for multipart parsing. You consume Multer through interceptors rather than wiring middleware manually.

  • FileInterceptor — one file from a single field
  • FilesInterceptor — many files from one field
  • FileFieldsInterceptor — files across several named fields

This lesson focuses on the first two and on enforcing size limits.

Installing the Types

The interceptors live in @nestjs/platform-express, which is already present in a standard Nest app. You only need the Multer type definitions to type your handler parameters correctly.

Install the dev dependency so Express.Multer.File is recognized by TypeScript:

npm install -D @types/multer

// Now Express.Multer.File is available globally in TypeScript.
// It describes the in-memory/disk file object Multer attaches
// to the request, e.g. originalname, mimetype, size, buffer, path.

Single File with FileInterceptor

Bind FileInterceptor('field') with @UseInterceptors, where the string is the name of the form-data field carrying the file. Then read the parsed file with the @UploadedFile() decorator.

The decorated parameter is a single Express.Multer.File. Notice the parameter name in the form does not need to match the handler argument — only the interceptor's field string matters.

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

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

Memory vs Disk Storage

By default Multer uses memory storage: the whole file lands in file.buffer as a Buffer. That is convenient for forwarding to S3 or processing in-process, but large files can exhaust RAM.

For local persistence use disk storage, where Multer streams to a path and gives you file.path instead of a buffer. Pass options as the second argument of the interceptor.

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

export const imageStorage = diskStorage({
  destination: './uploads/images',
  filename: (_req, file, cb) => {
    const unique = randomUUID();
    cb(null, `${unique}${extname(file.originalname)}`);
  },
});

// Usage:
// @UseInterceptors(FileInterceptor('photo', { storage: imageStorage }))

Enforcing a Size Limit

Never trust client-declared sizes. Cap the bytes Multer will accept via the limits.fileSize option (in bytes). When a file exceeds it, Multer aborts and Nest surfaces a 413-style error before your handler runs.

Combine fileSize with files to also bound the count of files in a multi-upload.

import { FileInterceptor } from '@nestjs/platform-express';

const FIVE_MB = 5 * 1024 * 1024;

@Post('avatar')
@UseInterceptors(
  FileInterceptor('avatar', {
    limits: { fileSize: FIVE_MB },
  }),
)
upload(@UploadedFile() file: Express.Multer.File) {
  return { stored: file.originalname };
}

Computing Limits Safely

Express limits are expressed in raw bytes, which is easy to get wrong by an order of magnitude. A tiny pure helper keeps the math explicit and testable, and it runs anywhere with no framework.

Below, mb converts megabytes to bytes and we sanity-check a candidate upload size against a cap.

function mb(n: number): number {
  return n * 1024 * 1024;
}

function withinLimit(sizeBytes: number, capMb: number): boolean {
  return sizeBytes <= mb(capMb);
}

const FILE_CAP_MB = 5;
console.log('5MB in bytes:', mb(FILE_CAP_MB));
console.log(withinLimit(mb(4), FILE_CAP_MB));   // true
console.log(withinLimit(mb(6), FILE_CAP_MB));   // false
console.log(withinLimit(5_242_880, FILE_CAP_MB)); // true (exactly 5MB)

Multiple Files with FilesInterceptor

FilesInterceptor('field', maxCount, options) accepts several files sent under the same field name. Read them with @UploadedFiles(), which yields an array.

The maxCount argument is a hard ceiling on how many files Nest will collect; extras trigger an error. Pair it with limits.fileSize for per-file byte caps.

import { Controller, Post, UploadedFiles, UseInterceptors } from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';

@Controller('gallery')
export class GalleryController {
  @Post()
  @UseInterceptors(
    FilesInterceptor('photos', 10, {
      limits: { fileSize: 5 * 1024 * 1024 },
    }),
  )
  upload(@UploadedFiles() files: Express.Multer.File[]) {
    return files.map((f) => ({ name: f.originalname, size: f.size }));
  }
}

Filtering by MIME Type

Size limits do not stop the wrong file type. Use fileFilter to accept or reject each part as it streams. Call the callback with (null, true) to keep a file or with an error to reject it.

Rejecting with a BadRequestException produces a clean 400 instead of a generic failure.

import { BadRequestException } from '@nestjs/common';
import { Request } from 'express';

export function imageFileFilter(
  _req: Request,
  file: Express.Multer.File,
  cb: (error: Error | null, accept: boolean) => void,
) {
  const allowed = ['image/png', 'image/jpeg', 'image/webp'];
  if (!allowed.includes(file.mimetype)) {
    return cb(new BadRequestException('Only PNG, JPEG, or WebP allowed'), false);
  }
  cb(null, true);
}

Validating with ParseFilePipe

Nest's built-in ParseFilePipe validates the already-parsed file declaratively inside the handler. It composes validators like MaxFileSizeValidator and FileTypeValidator, returning a 422 when they fail.

This is complementary to Multer's limits: Multer guards the stream, the pipe guards your business rules and gives clearer error messages.

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

@Post('avatar')
@UseInterceptors(FileInterceptor('avatar'))
upload(
  @UploadedFile(
    new ParseFilePipe({
      validators: [
        new MaxFileSizeValidator({ maxSize: 5 * 1024 * 1024 }),
        new FileTypeValidator({ fileType: /(png|jpe?g|webp)$/ }),
      ],
    }),
  )
  file: Express.Multer.File,
) {
  return { ok: true, name: file.originalname };
}

Centralizing Config with a Factory

Repeating storage, limits, and filters on every route is error-prone. Extract a single MulterOptions object (or a factory) and reuse it. Enterprise apps often register defaults globally via MulterModule.register() and override per-route only when needed.

This keeps caps consistent and makes raising a limit a one-line change.

import { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface';
import { diskStorage } from 'multer';
import { imageFileFilter } from './image-file.filter';

export const imageUploadOptions: MulterOptions = {
  storage: diskStorage({ destination: './uploads/images' }),
  limits: { fileSize: 5 * 1024 * 1024, files: 10 },
  fileFilter: imageFileFilter,
};

// @UseInterceptors(FilesInterceptor('photos', 10, imageUploadOptions))

Handling the Size-Limit Error

When limits.fileSize is exceeded, Multer throws an error whose code is 'LIMIT_FILE_SIZE'. By default Nest wraps it, but you can map it to a friendly payload with an exception filter so clients get a clear, consistent message.

Translating low-level Multer codes into HTTP responses is a hallmark of production-grade upload endpoints.

import { ExceptionFilter, Catch, ArgumentsHost, HttpStatus } from '@nestjs/common';
import { MulterError } from 'multer';
import { Response } from 'express';

@Catch(MulterError)
export class MulterExceptionFilter implements ExceptionFilter {
  catch(err: MulterError, host: ArgumentsHost) {
    const res = host.switchToHttp().getResponse<Response>();
    const status =
      err.code === 'LIMIT_FILE_SIZE'
        ? HttpStatus.PAYLOAD_TOO_LARGE
        : HttpStatus.BAD_REQUEST;
    res.status(status).json({ statusCode: status, message: err.message });
  }
}

Quick Check

Test your understanding of choosing the right interceptor and reading its result.

Recap

You can now wire multipart uploads end to end in NestJS:

  • FileInterceptor('field', options) + @UploadedFile() for one file.
  • FilesInterceptor('field', maxCount, options) + @UploadedFiles() for many files under one field.
  • limits.fileSize (bytes) caps stream size; limits.files caps count; fileFilter rejects bad MIME types early.
  • diskStorage vs memory storage decides whether you get file.path or file.buffer.
  • ParseFilePipe with MaxFileSizeValidator/FileTypeValidator validates declaratively, and a MulterError filter maps LIMIT_FILE_SIZE to a clean 413.

Centralize these options in one factory so limits stay consistent across every upload route.

자주 묻는 질문

“Multer 인터셉터를 사용한 멀티파트 업로드” 강의는 무료인가요?

네 — “Multer 인터셉터를 사용한 멀티파트 업로드” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

“Multer 인터셉터를 사용한 멀티파트 업로드”에서 뭘 배우나요?

FileInterceptor와 FilesInterceptor를 연결해 크기 제한이 있는 단일 파일 및 여러 파일 업로드를 처리합니다 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“Multer 인터셉터를 사용한 멀티파트 업로드” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Multer 인터셉터를 사용한 멀티파트 업로드
  2. StreamableFile로 대용량 응답 스트리밍하기
  3. 사전 서명 URL을 사용한 S3 직접 업로드
  4. Sharp를 사용한 이미지 처리 파이프라인
← NestJS Enterprise Backend APIs(으)로 돌아가기