배포 후 S3 사용해 이미지 저장

개발공부·2023년 2월 9일
0

* 결과

1) 프로필 변경

2) 게시글 이미지 추가해 게시글 작성

[S3 버킷 만들기 - AWS]

  1. s3에서 버킷 만들기 > "이 버킷의 퍼블릭 액세스 차단 설정" 비활성화하기
    ▶ 모든 사람들이 접속하는 서비스이므로
    ▶ 생성 시 액세스가 객체를 퍼블릭으로 설정할 수 있음라고 나와야 함

  2. 해당 버킷 이름 들어가기 > 권한 내 '버킷 정책' 들어가기
    ▶ 편집 누르고 아래의 내용 넣기

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AddPerm",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::버킷이름/*"
        }
    ]
}
  1. 자신의 이름 클릭 > 보안 자격 증명 누르기 > 액세스 키 > 액세스 키 만들기
    ▶ 만들고 다운받기(.csv 파일임)

  2. backend 폴더에 multer-s3와 aws-sdk 다운 받기

npm i multer-s3 aws-sdk

  1. backend 폴더 .envS3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY 추가(.csv 파일에서 얻은 정보)

  2. routes/post.js
    ▶ 기존의 이미지 주소가 http://%{backUrl}/v 이런 식이었다면
    s3 연결 이후 v만 입력해도 됨

  • routes/post.jsroutes/user.js가 동일하게 들어가는 내용
const multerS3 = require("multer-s3");
const AWS = require("aws-sdk");

AWS.config.update({
  accessKeyId: process.env.S3_ACCESS_KEY_ID,
  secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
  region: "ap-northeast-2",
});
  • 기존 저장 내용
const upload = multer({
  storage: multer.diskStorage({
    destination(req, file, done) {
      done(null, "uploads");
    },
    filename(req, file, done) {
      //파일이미지.png
      const ext = path.extname(file.originalname); //확장자 추출(.png)
      const basename = path.basename(file.originalname, ext); //파일이미지
      done(null, basename + "_" + new Date().getTime() + ext); //파일이미지1234849.png
    },
  }),
  limits: { fileSize: 20 * 1024 * 1024 }, // 20MB
});

router.post(
  "/images",
  isLoggedIn,
  upload.array("image"),
  async (req, res, next) => {
    console.log("req.files", req.files);
    res.json(req.files.map((v) => v.filename));
  }
);
  • 바뀐 저장 내용
const upload = multer({
  storage: multerS3({
    s3: new AWS.S3(),
    bucket: "버킷 이름", 
    key(req, file, cb) {
      cb(null, `original/${Date.now()}_${path.basename(file.originalname)}`);
    },
  }),
  limits: { fileSize: 20 * 1024 * 1024 }, // 20MB
});

router.post(
  "/images",
  isLoggedIn,
  upload.array("image"),
  async (req, res, next) => {
    console.log("req.files", req.files);
    res.json(req.files.map((v) => v.location));
  }
);
  1. router/user.js (참고 블로그)
    ▶ 프로필 이미지는 이미지 저장 후 바로 me 정보에 저장됨(User.update)
  • 기존 저장 내용
const upload = multer({
  storage: multer.diskStorage({
    destination(req, file, done) {
      done(null, "uploads/userImg");
    },
    filename(req, file, done) {
      //파일이미지.png
      const ext = path.extname(file.originalname); //확장자 추출(.png)
      const basename = path.basename(file.originalname, ext); //파일이미지
      done(null, basename + "_" + new Date().getTime() + ext); //파일이미지1234849.png
    },
  }),
  limits: { fileSize: 20 * 1024 * 1024 }, // 20MB
});

router.post(
  "/image",
  isLoggedIn,
  upload.single("image"),
  async (req, res, next) => {
    await User.update(
      { profileImg: req.file.filename },
      { where: { id: req.user.id } }
    );
    res.json(req.file);
    console.log("req.file", req.file);
  }
);
  • 바뀐 저장 내용

기존 파일명이 req.filereq.file.filename이었다면
s3 적용 후 req.file.location으로 적용됨

const upload = multer({
  storage: multerS3({
    s3: new AWS.S3(),
    bucket: "버킷 이름", 
    key(req, file, cb) {
      cb(
        null,
        `original/profileImg/${Date.now()}_${path.basename(file.originalname)}`
      );
    },
  }),
  limits: { fileSize: 20 * 1024 * 1024 }, // 20MB
});


router.post(
  "/image",
  isLoggedIn,
  upload.single("image"),
  async (req, res, next) => {
    await User.update(
      { profileImg: req.file.location },
      { where: { id: req.user.id } }
    );
    res.json(req.file.location);
    console.log("req.file", req.file.location);
  }
);

* 오류

aws ssh 접속 시 Conntection timed out이라고 뜸

참고 블로그

* 오류 2

이미지 올렸을 때 500에러가 뜸

  • 오류 2 에러 코드
this.client.send is not a function
    at Upload.__uploadUsingPut

참고 블로그

muter와 aws-sdk 간 버전을 동일시 함

// 2.XX 버전 재설치
npm i multer-s3@^2 --save

* 오류 3

Error: Region is missing

▶ @aws-sdk/client-s3 삭제(다른 사이트 해결책 중 시도하다가 지우는 것을 잊어버림)

npm uninstall @aws-sdk/client-s3

profile
개발 블로그, 티스토리(https://ba-gotocode131.tistory.com/)로 갈아탐

0개의 댓글