Develop/[NestJs]
[NestJs] S3업로드 모듈 생성
HiSmith
2023. 6. 26. 20:59
반응형
1. 업로드 사용 모듈 생성
nest g mo uploads
nest g co uploads
nest g s uploads
2.디펜던시 추가 Express module multer 추가
npm i -g @types/multer
3. aws-sdk 및 multer-s3 추가.
npm i -D aws-sdk --force
npm i -D multer-s3 --force
4. aws s3 설정과 iam으로 사용자를 생성해서 토큰값을 넣어준다.
아래 사이트 참고해서 설정을 진행하자.
https://soraji.github.io/back/2023/02/14/awsS3/
5. 컨트롤러
import {
Controller,
Post,
UploadedFiles,
UseInterceptors,
} from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';
import { UploadsService } from './uploads.service';
@Controller('uploads')
export class UploadsController {
constructor(private readonly uploadsService: UploadsService) {}
@Post('')
@UseInterceptors(FilesInterceptor('files', 10)) // 10은 최대파일개수
async uploadFile(@UploadedFiles() files) {
console.log(files);
const imgurl: string[] = [];
await Promise.all(
files.map(async (file: Express.Multer.File) => {
const key = await this.uploadsService.uploadImage(file);
imgurl.push(""+key);
}),
);
return {
statusCode: 201,
message: `이미지 등록 성공`,
data: imgurl,
};
}
}
6.서비스
import { Injectable } from '@nestjs/common';
import * as AWS from 'aws-sdk';
@Injectable()
export class UploadsService {
private readonly s3;
constructor() {
AWS.config.update({
//region: process.env.AWS_REGION,
region: 'ap-northeast-2',
credentials: {
accessKeyId: '비밀',
secretAccessKey: '비밀',
},
});
this.s3 = new AWS.S3();
}
async uploadImage(file: Express.Multer.File) {
console.log('construct');
const key = `${Date.now() + file.originalname}`;
console.log(key);
const params = {
Bucket: '비밀',
ACL: 'public-read',
Key: key,
Body: file.buffer,
};
return new Promise((resolve, reject) => {
this.s3.putObject(params, (err, data) => {
console.log(err);
console.log(params);
console.log(data);
if (err) reject(err);
resolve(key);
});
});
}
}
//리턴 타입
// export interface SendData {
// /**
// * URL of the uploaded object.
// */
// Location: string;
// /**
// * ETag of the uploaded object.
// */
// ETag: string;
// /**
// * Bucket to which the object was uploaded.
// */
// Bucket: string;
// /**
// * Key to which the object was uploaded.
// */
// Key: string;
// }
이렇게 하면, 해당 성공 or 실패를 전달 받을 수 있는 코드가 대략적으로 구현이 된다.
환경마다 파일로 빼서 해당 토큰 및 키를 관리할 예정이다...(다음 포스팅때)
또한 여러개의 파일을 저장할 수 있다.
그럼 오늘은 이만 끗
반응형