NestJS Server에 저장된 파일을 AWS S3버킷에 업로드 하기 - 1 : 서버의 파일을 올리기
안녕하세요. 이번에는 NestJS에 저장된 파일을 S3버킷에 올리도록 하겠습니다.
이전글 : NestJS Server에 저장된 파일을 AWS S3버킷에 업로드 하기 - 0 : AWS S3 버킷 및 IAM셋팅
npm 설치 : aws-sdk
- aws의 s3버킷과 통신을 하기 위한 패키지를 설치한다.
$ npm i aws-sdk
![]() |
사진1) 폴더 및 파일 생성 |
사진1과 같이 aws폴더를 만들어 주고 3개의 파일을 생성합니다.
// /src/aws/aws.service.ts
import { HttpException, Injectable } from '@nestjs/common';
import * as AWS from 'aws-sdk';
import * as fs from 'fs';
import * as path from 'path';
// 현재 실행되고 있는 root경로를 확인하고 pa에 저장
const pa = path.dirname(__dirname).replace('/dist', '');
@Injectable()
export class AwsService {
// S3버킷을 .env파일에서 입력한다.
private AWS_S3_BUCKET = process.env.S3_BUCKET;
// s3를 사용하기 위해서 IAM계정의 ACCESS, SECRET_ACCESS KEY를 입력한다.
private s3 = new AWS.S3({
accessKeyId: process.env.S3_ACCESS_KEY,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
});
convertBinary(fileName: string) {
return fs.readFileSync(pa + '/uploads/' + fileName);
}
// AWS 버킷에 파일 upload
async uploadFile(file) {
// savename은 실제 S3 버킷에 저장될시 파일 이름을 말합니다
const { savename } = file;
console.log('savename : ', savename);
return await this.s3_upload(
file.buffer, // 파일 버퍼(binary file)
this.AWS_S3_BUCKET, // 저장할 S3버킷 이름
savename, // S3버킷에 저장할 파일 이름
file.mimetype, // 파일타입 : 위 코드에서는 'application/octet-stream'을 사용합니다.
);
}
// 실제 AWS에 파일을 업로드 하는 method
async s3_upload(file, bucket, name, mimetype) {
const params = {
Bucket: bucket,
Key: String(name),
Body: file,
ACL: 'public-read',
ContentType: mimetype,
ContentDisposition: 'inline',
CreateBucketConfiguration: {
LocationConstraint: process.env.s3_REGION,
},
};
console.log(params);
try {
let s3Response = await this.s3.upload(params).promise();
console.log(s3Response);
return s3Response;
} catch (err) {
console.log(err);
throw new HttpException(err.message, err.status ? err.status : 500);
}
}
}
코드1) service code
// /src/aws/aws.controller.ts
import { Controller, Get, Query } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { AwsService } from './aws.service';
@ApiTags('AWS S3 버킷으로 파일을 올리기')
@Controller('aws')
export class AwsController {
constructor(private readonly awsService: AwsService) {}
@Get('aws/upload/storage/file')
@ApiOperation({
summary: 'AWS S3버킷으로 저장된 파일을 전송합니다.',
})
async uploadStorage(
@Query('fileName') fileName: string,
@Query('saveName') saveName: string,
) {
// 해당 파일을 전송 가능하도록 binary로 변환한다
const binary = this.awsService.convertBinary(fileName);
// 필요 내용을 file Object로 저장한다.
const file = {
buffer: binary,
savename: saveName,
mimetype: 'application/octet-stream',
};
return await this.awsService.uploadFile(file);
}
}
코드2) controller code
코드를 보시면 먼저 파일을 binary code로 저장을 하고 이것을 file Object로 모아서 AWS로 보내줍니다.
그리고 AWS에서 받은 ACCESS, SECRET키가 필요합니다. 이는 해당 자료(링크)를 확인해 주시기 바랍니다.
![]() |
사진2) 업로드 파일 저장 |
사진2에서 제가 NestJS 프로젝트 안에 'uploads'폴더를 만들고 안에 'music.mp3'파일을 저장했습니다.
![]() |
사진3) Swagger로 테스트 |
{
"Location": "다운로드 가능한 S3버킷 url",
"Bucket": "버킷 명칭",
"Key": "saveName",
"ETag": "Return Code"
}
코드3) server 리턴값
Swagger에서 NestJS서버에 존재하는 파일(여기서는 music.mp3)과 S3버킷에 저장할 이름을 입력하고 실행을 하면 코드3와 같이 응답이 옵니다.
이때 S3버킷에서 다운로드 가능한 url로 해당 파일을 다운로드 할수 있습니다.
GitHub branch(uploadFromStorage) URL
다음글 : NestJS Server에 저장된 파일을 AWS S3버킷에 업로드 하기 - 2 : 클라이언트에서 받은 파일을 올리기
댓글
댓글 쓰기