NestJS에서 AWS S3에 이미지 업로드 API 작성

이미지 파일(png, jpg 등)을 AWS S3에 업로드하는 기능을 추가해야하는 일이 생겼다.

이미지 업로드 API를 구축할 때, 다음과 같이 NestJS에서 기본적으로 제공하는 UseInterceptors와 FileInterceptor를 사용하여 API를 호출하여 파일을 전달하는 방식으로 하였다. 

@Post()
@UseInterceptors(FileInterceptor('file'))
async uploadPhoto(@UploadedFile() file) {
    const { Key, Location } = await this.awsService.addToPublic('photos', file);
    return this.photoService.save({
      url: Location,
      key: Key,
    });
  }
private async upload(key: string, file: File, acl: string) {
    const fileType = file.mimetype;
    const fileBuffer = file.buffer;
    return this.s3
      .upload({
        Bucket: this.bucketName,
        Key: key,
        Body: fileBuffer,
        ContentType: fileType,
        ContentEncoding: file.encoding,
        ACL: acl,
      })
      .promise();
  }

generateKey(path: string, filename: string) {
    return `${path}/${Date.now()}_${filename}`;
  }


addToPublic(path: string, file: File) {
    const filename = file.filename;
    const key = this.generateKey(path, filename);
    return this.upload(key, file, 'public-read');
  }

 

파일을 이미지 업로드 API를 통해 전송하면, 파일에서 파일 이름을 가져와서 generateKey( )함수를 통해 Key 값을 생성하고, 이 생성된 Key값과, 파일을 AWS S3에 업로드하고, 데이터베이스에 해당 Key값과 Location을 저장하는 방식입니다.

 

출처) https://github.com/jaeyeon93

 

jaeyeon93 - Overview

jaeyeon93 has 69 repositories available. Follow their code on GitHub.

github.com