개발일지

Nest.JS AWS S3 적용

index.ys 2023. 8. 20. 00:37

컨트롤러

  • 사진업로드를 위해 라우터 핸들러에서 이미지 파일을 받아 AWS S3에 업로드 하는 인터셉터를 작성
  //AWS S3에 이미지 파일을 업로드 하는 인터셉터
  @UseInterceptors(S3FileInterceptor)
  async uploadFile(@UploadedFiles() files: Express.Multer.File[]) {
    try {
      const [url] = files;
      console.log(files, url);
      return '성공';
    } catch (error) {
      console.error(error);
    }
  }

 

S3FileInterceptort

  • interceptor 폴더생성후 S3인터셉터 코드 작성 후 export하여 라우터 핸들러에 인터셉터 적용
import { Injectable } from '@nestjs/common';
import * as AWS from 'aws-sdk';
import * as multerS3 from 'multer-s3';
import { FilesInterceptor } from '@nestjs/platform-express/multer/interceptors/files.interceptor';
import path from 'path';
import sharp from 'sharp';

@Injectable()
//파일의 최대 갯수를 3개로 제한
export class S3FileInterceptor extends FilesInterceptor('file', 3, {
  storage: multerS3({
  //AWS S3의 리전을 환경 변수로 선언
    s3: new AWS.S3({
      region: process.env.AWS_REGION,
      credentials: {
      //AWS IAM 액세스키와 시크릿 키를 환경 변수로 선언
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
      },
    }),
    //AWS S3 버킷이름을 환경 변수로 선언
    bucket: process.env.AWS_S3_BUCKET_NAME,
    //S3권한 설정
    acl: 'public-read',
    contentType: multerS3.AUTO_CONTENT_TYPE,
    shouldTransform: true,
    transforms: [
      {
        id: 'resized',
        key: function (req, file, cb) {
          let extension = path.extname(file.originalname);
          cb(null, Date.now().toString() + extension);
        },
        transform: function (req, file, cb) {
          cb(null, sharp().resize(100, 100)); // 이미지를 100x100 으로 리사이징
        },
      },
    ],
    key: function (request, file, cb) {
      cb(null, `${Date.now().toString()}-${file.originalname}`);
    },
  }),
  //이미지 크기 제한을 25mb로 제한
  limits: { fileSize: 5 * 1024 * 1024 },
}) {}

사진 업로드

  • 서버 실행 후 localhost:3000/api/reportuser 주소로 file 3장 전송

요청 로그

  • /api/reportuser 경로로 post 요청시 전송한 사진 3장이 업로드 된 것을 확인

AWS S3 버킷

  • 방금 업로드한 사진 3장이 그대로 업로드 된 것을 확인