[Express] AWS s3와 node.js 연결해서 이미지 올리기

찐찐·2022년 3월 25일
4

AWS s3 <-> Node.js

목록 보기
1/2
post-thumbnail

multer 모듈

node.js에서 이미지(파일, multipart/from-data)를 올리기 위한 모듈이다.

기본적인 사용법

  1. npm install multer로 모듈을 설치해준다.
const multer = require('multer');

const upload = multer({
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
        cb(null, './upload/');
        },
        filename: function (req, file, cb) {
        cb(null, Date.now() + "-" + file.originalname);
        }
    })
});
  • destination: 어느 폴더에 저장할지 지정
  • filename: 폴더 안에 저장되는 파일명 결정에 사용
    • 지정하지 않으면 랜덤하게 지정된다. (이럴 경우 나중에 불러와서 띄우기 힘들어진다.)
    • multer는 파일 확장자를 추가하지 않기 때문에 확장자가 포함된 온전한 파일명이 필요하다.
  1. multer 객체 설정이 끝나면, 라우터에 추가해 사용할 수 있다.
app.post('endpoint', upload.single('photo'), async (req, res) => {
	// 어떤 동작
  	console.log(req.file);
});
  • req.file에 파일 정보가 들어오게 된다.
  • 업로드는 위에 지정한 저장소(storage)에 된다.
  • 하나의 파일 업로드를 위한 upload.single() 외에도, upload.array(), upload.fields() 여러 사용법이 있다.
    • 얘네는 req.files에 파일 정보가 저장된다.
    • upload.array('photo', 12): 12개의 파일 정보를 배열로 갖고 있는다.
    • upload.fields([{ name: 'photo', maxCount: 1}, { name: 'photo2', maxCount: 2}]):
      • req.files['photo'][0] -> 각 File에 대한 정보
      • req.files['photo2'] -> File들의 Array

AWS s3와 연결

사용법은 위와 동일하고 storage만 s3 bucket으로 변경해서 사용하면 된다.

  1. 버킷과 연결하기 위해 S3 객체 생성
  • aws key는 aws 콘솔 → 보안 자격 증명에서 받을 수 있다.
  • npm install aws-sdk로 모듈 설치
const aws = require('aws-sdk');

const s3 = new aws.S3({
    accessKeyId: aws_key.access,
    secretAccessKey: aws_key.secret,
    region: aws_key.region
});
  1. S3와 multer를 연결하기 위해 multer-s3 모듈을 사용해 storage 객체를 생성한다.
  • npm install multer-s3
const multer = require('multer');
const multer_s3 = require('multer-s3');

const storage = multer_s3({
    s3: s3,
    bucket: '-', // 자신의 s3 버킷 이름
    contentType: multer_s3.AUTO_CONTENT_TYPE,
    acl: 'public-read', // 버킷에서 acl 관련 설정을 풀어줘야 사용할 수 있다.
    metadata: function(req, file, cb) {
        cb(null, {fieldName: file.fieldname});
    },
    key: function (req, file, cb) {
        cb(null, `contents/${Date.now()}_${file.originalname}`);
    }
})

const upload = multer({
    storage: storage // storage를 multer_s3 객체로 지정
})
  • acl 설정에 관한 오류가 발생했었다. The bucket does not allow ACLs였는데, bucket에 acl 관련 설정을 주지 않아 발생한 오류였다.
    bucket → 권한 → 퍼블릭 액세스 차단: 비활성 → 객체 소유권: ACL 활성 → ACL: 모든 사람에게 읽기 권한으로 해결 (aws에선 권장하지 않는 방법이라고 하니 보안이 중요하다면 다른 방법을 찾을 것)

여기까지 하면 연결 완료, 이제 라우터만 제대로 설정하면 잘 올라갈 것이다.

  1. 테스트
const express = require('express');
const app = express();

const upload = upload.fields([{name: 'photo', maxCount: 1}, {name: 'thumbnail', maxCount: 1}]) 
app.post('/', upload, async (req, res) => {
	const photo = req.files['photo'][0];
  	cosnt thumbnail = req.files['thumbnail'][0];
  	
  	console.log(photo, thumbnail);
});

app.listen(5000);

이런 식으로 간단하게 코드를 짜고 postman으로 테스트를 해보면, s3 bucket에 데이터가 제대로 들어간 것을 확인할 수 있다.

profile
백엔드 개발자 지망생

0개의 댓글