📌 이 글은 THE SOPT 30기 서버파트 7차 세미나에서 학습한 내용을 다룹니다.
application/json
multipart/form-data
multer
multipart/form-data로 전송된 파일 처리 미들웨어
multer-s3
이미지 업로드 시 S3를 사용할 경우 이용
aws-sdk
Node.js용 AWS SDK를 사용하기 위한 모듈
yarn add multer multer-s3 aws-sdk
yarn add @types/multer-s3 @types/multer --dev
import AWS from "aws-sdk";
import config from ".";
const s3: AWS.S3 = new AWS.S3({
accessKeyId: config.s3AccessKey,
secretAccessKey: config.s3SecretKey,
region: "ap-northeast-2",
});
export default s3;
import multer from "multer";
import multerS3 from "multer-s3";
import config from ".";
import s3 from "./s3Config";
const upload = multer({
// 미들웨어로 사용할 multer 생성
storage: multerS3({
s3: s3, // 실질적인 storage는 multerS3 이용해 aws s3로 설정
bucket: config.bucketName, // s3 bucket name 지정
contentType: multerS3.AUTO_CONTENT_TYPE, // mimetype은 자동으로 설정
acl: "public-read", // Access control for the file
key: function (req: Express.Request, file: Express.MulterS3.File, cb) {
// key -> 파일 이름 정의
cb(null, `${Date.now()}_${file.originalname}`); // bucket 내에서 이름이 겹치면 동일 파일로 인식해서 보통 고유하게 만든다.
},
}),
});
export default upload;
router.post('/upload', upload.single('file'), FileController.uploadFileToS3);
router에서 middleware로 사용
single
: 파일 한 개, req.file
로 받아옴
array
: 파일 여러 개, req.files
로 받아옴