npm install multer-s3 @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
필요한 모듈을 설치한다.
AWS S3 버킷 생성
https://velog.io/@minjae98/AWS-AWS-S3-%EB%B2%84%ED%82%B7-%EC%83%9D%EC%84%B1
AWS IAM 권한 조정
https://velog.io/@minjae98/AWS-AWS-IAM-%EA%B6%8C%ED%95%9C-%EC%84%A4%EC%A0%95
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' };
}
// 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('파일 업로드에 실패했습니다.');
}
}
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;
}