[SOPT] 7차 세미나 - 이미지 업로드

공혁준·2022년 5월 28일
0

SOPT 활동

목록 보기
8/8
post-thumbnail

📌 이 글은 THE SOPT 30기 서버파트 7차 세미나에서 학습한 내용을 다룹니다.

Content Type

application/json

  • HTTP Body에 들어가는 Message의 Type을 명시
  • json 형식을 사용해서 HTTP Body를 전송하는 경우의 Content Type

multipart/form-data

  • Content-Type 필드에 MIME Type을 명시하기 위한 Content-Type
  • File 전송을 위해 사용한다!

Client - Server 업로드 과정

  1. 클라이언트는 Form을 통해서 파일을 서버로 전송
  2. Content-Type이 multipart/form-data로 지정 되어 전송
  3. 서버는 해당 multipart 메시지를 part 별로 분리하여 처리

파일 업로드를 도와 줄 유용한 모듈

multer
multipart/form-data로 전송된 파일 처리 미들웨어

multer-s3
이미지 업로드 시 S3를 사용할 경우 이용

aws-sdk
Node.js용 AWS SDK를 사용하기 위한 모듈

multer, multer-s3, aws-sdk 설치

yarn add multer multer-s3 aws-sdk
yarn add @types/multer-s3 @types/multer --dev

S3 연결

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;

multer 설정

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로 받아옴

profile
몰입을 즐기는 개발자입니다.

0개의 댓글