[AWS] AWS S3 사용법

김민재·2024년 9월 27일
0

AWS

목록 보기
11/14

S3 프로세스

  • 게시글에 이미지를 S3 버킷에 저장하여, DB에는 그 버킷의 이미지 파일 경로를 저장하고, 서버는 이 경로를 클라이언트로 응답하는 식으로 구축

multer-s3

  • node.js에는 multer을 이용하여 이미지, 동영상 같은 파일을 업로드 하는 경우가 많다. multer-s3 모듈을 사용하여 AWS S3를 이용할 수 있다.

multer-s3 사용법

  1. npm install multer-s3 @aws-sdk/client-s3 @aws-sdk/s3-request-presigner 필요한 모듈을 설치한다.

  2. AWS S3 버킷 생성

    https://velog.io/@minjae98/AWS-AWS-S3-%EB%B2%84%ED%82%B7-%EC%83%9D%EC%84%B1

  3. AWS IAM 권한 조정

    https://velog.io/@minjae98/AWS-AWS-IAM-%EA%B6%8C%ED%95%9C-%EC%84%A4%EC%A0%95

  1. controller에서 설정을 해준다.

    @Post()
    @UseInterceptors(FileInterceptor('image')) // 이미지 업로드 처리
    @UseGuards(JwtAuthGuard)
    async create(
      @UserInfo() user: User,
      @Body() createBoardDto: CreateBoardDto,
      @UploadedFile() file: Express.MulterS3.File,
    ) {
      const { title } = createBoardDto;
    
      if (title.trim() === '') {
        throw new BadRequestException({
          success: false,
          message: '공백만 사용할 수는 없습니다',
        });
      }
    
      let imagePath = null;
    
      if (file) {
        imagePath = await this.boardService.uploadFile(file); // S3에 업로드 후 URL 반환
      }
    
      await this.boardService.create(
        createBoardDto,
        user.name,
        imagePath,
        user.id,
      );
    
      return { success: true, message: 'okay' };
    }
  1. service 수정해준다.
  // S3에 파일 업로드 메서드
  async uploadFile(file: Express.Multer.File): Promise<string> {
    const uploadParams = {
      Bucket: 'blog-image-s3',
      Key: `${Date.now().toString()}-${file.originalname}`,
      Body: file.buffer, // 파일의 버퍼
      ContentType: file.mimetype,
    };

    try {
      const command = new PutObjectCommand(uploadParams);
      await this.s3Client.send(command);
      // S3에서의 파일 URL 반환
      return `https://${uploadParams.Bucket}.s3.amazonaws.com/${uploadParams.Key}`;
    } catch (error) {
      console.error('Error uploading file:', error);
      throw new Error('파일 업로드에 실패했습니다.');
    }
  }
  1. nest를 사용할 경우 multerS3는 타입을 지정해줘야한다.
    6-1. @types 폴더를 프로젝트 루트에 생성 - multer-s3.d.ts 파일 생성

    declare module 'multer-s3' {
    import { StorageEngine } from 'multer';
     import { S3 } from 'aws-sdk';
    
     interface MulterS3Options {
     s3: S3;
     bucket: string;
      acl?: string;
      key: (req: any, file: any, cb: (error: any, key: string) => void) => void;
    }
    
      function multerS3(options: MulterS3Options): StorageEngine;
    
      export = multerS3;
     }
profile
개발 경험치 쌓는 곳

0개의 댓글

관련 채용 정보