File

장현욱(Artlogy)·2022년 11월 28일
0

Nest.js

목록 보기
18/18
post-thumbnail

FileUpload

먼저 파일업로드에 필요한 multer 패키지를 받아주자.

#npm
npm i -D @types/multer
#yarn
yarn add -D @types/multer

위 패키지가 설치되면 Express.Multer.File유형을 사용할 수 있다.

단일파일 업로드

가장 간단한 단일 파일업로드는 다음과 같이 처리한다.

  @ApiOperation({
    summary: '단일 파일 업로드',
    description: '단일 파일을 업로드하기 위한 실험적 API',
    deprecated: true,
  })
  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  @ApiConsumes('multipart/form-data')
  uploadFile(
    @UploadedFile() file: Express.Multer.File,
    @Body() dto: RequestFileDto,
  ) {
    console.log(file, dto);
  }

FileInterceptor(fieldName, options)

@UploadFile()데코레이터를 통해 request에서 파일을 추출한다.

  • fieldName:파일이 정보가 존재하는 필드명
  • options: MulterOptions 타입의 선택적객체 (validate 설정이 가능하다)

@ApiConsumes()

  • swagger에서 request content-type을 정해주는 데코레이터

file을 포함한 DTO

혹시 모르는 사람도 있을지 몰라 예제로 기록해둠

export class RequestFileDto extends PickType(File, ['origin_name'] as const) {
  @ApiProperty({ type: 'string', format: 'binary', description: '파일' })
  file: Express.Multer.File;
}

Custom Decorator로 정리하기

export const CustomFileUpload = (field: string, options?: MulterOptions) => {
  return applyDecorators(
    UseInterceptors(FileInterceptor(field, options)),
    ApiConsumes('multipart/form-data'),
  );
};

정적 컨텐츠 제공하기

설치

#npm
$ npm i -s @nestjs/serve-static

#yarn
$ yarn add @nestjs/serve-static

app.module.ts

    ServeStaticModule.forRoot({
      rootPath: join('파일이 저장된 위치'),
    }),


잘나온다.

단일파일 다운로드

@Get(':path/:name')
    async download(@Res() res: Response, @Param('path') path: string, @Param('name') name: string, @Query('fn') fileName) {
        res.download(`${this.config.get('ATTACH_SAVE_PATH')}/${path}/${name}`, fileName);
    }

로컬 업로드 옵션 설정하기

// 로컬 파일 저장 위치
export const LOCAL_ATTACH_SAVE_PATH: string = path.join(
  __dirname,
  '../../',
  'public',
);
// 로컬 파일 저장옵션
export const localFileOptions: MulterOptions = {
  storage: diskStorage({
    destination: (req, file, callback) => {
      if (!existsSync(LOCAL_ATTACH_SAVE_PATH)) {
        // public 폴더가 존재하지 않을시, 생성합니다.
        mkdirSync(LOCAL_ATTACH_SAVE_PATH);
      }

      callback(null, LOCAL_ATTACH_SAVE_PATH);
    },
    filename(req, file, callback) {
      file['uuid'] = randomUUID();
      //저장될 파일이름은 이곳에서 정의된다.
      callback(null, `${file['uuid']}${path.extname(file.originalname)}`);
    },
  }),
};

파일용 config 파일을 만들고 위 처럼 정의된 옵션을 만들어주자.
그 후 다음처럼 옵션값 대신 넣어주면 된다.

@UseInterceptors(FileInterceptor('file', localFileOptions)),

0개의 댓글