[NestJS] multer를 사용하여 File upload하기

2024. 7. 11. 20:56NestJs

728x90
반응형

 

서론

이번에 NestJS에서 제공하는 File upload를 사용하여 사용자가 원하는 첨부파일을 데이터베이스에 업로드를 할 수 있게 하는 방식을 사용해보려고 합니다. 이번 글에서는 단일 파일만 업로드를 하는 방식을 하려고 합니다. 여러 파일을 업로드를 해야 한다는 공식사이트를 참고하시면 좋을 거 같습니다. 

 

multer란? 

multer는 Node.js 기반의 웹 애플리케이션에서 파일 업로드를 쉽게 처리할 수 있게 해주는 미들웨어입니다. multipart/form-data 형식으로 전송된 데이터를 해석하고 처리할 수 있어, 파일 업로드와 관련된 기능을 구현할 때 매우 유용합니다.

 

NestJS multer 사용방법

 

1. 라이브러리 설치

npm i -D @types/multer

 

NestJS는 Express용 multer 미들웨어를 내장 모듈로 제공하므로 @tpyes/multer를 설치합니다.

 

2. 컨트롤러 메서드 구현

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

@Controller('upload')
export class UploadController {

  @Post()
  @UseInterceptors(FileInterceptor('file'))
  uploadFile(@UploadedFile() file: Express.Multer.File) {
    console.log(file);
    // 파일 처리 로직 추가
  }
}

 

 

 

  • @UseInterceptors(FileInterceptor('file')): Multer 미들웨어를 적용하여 요청에서 파일 데이터를 추출
  • @UploadedFile(): 업로드된 파일 데이터를 Express.Multer.File 타입으로 받아옵니다.

3. 파일 검증 구현

import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';

@Injectable()
export class FileSizeValidationPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    // "value" is an object containing the file's attributes and metadata
    const oneKb = 1000;
    return value.size < oneKb;
  }
}

 

 

 

 

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

 

728x90
반응형