본문 바로가기

유통기한 관리_개인프로젝트

heroku 서버 - 이미지 업로드 오류 발생 - 이미지 직접 호스팅

개발 환경에서는 이미지 업로드 기능과 업로드 한 이미지를 가져오는 데 문제가 없었다.

그러나 heroku 서버에 배포 후 아래와 같은 문제점들이 발생했다.

herokuapp.com/images/NoImage.png 접근이 가능하지만 uploads폴더에 업로드 이미지가 정상적으로 저장이 안된다. 

기존에 있는 이미지는 읽어올 수 있는데 배포 후 새로 업로드한 이미지를 못읽어온다면, heroku가 배포했을때 그 상태의 파일만 읽어오고 이후에 새로 디스크에 추가된 파일들은 호스팅에서 지원하지 않는게 원인일 수도 있다는 생각이 들었다. 

 

그래서 이미지를 직접 호스팅하는 방안으로 찾아보았다.

devcenter.heroku.com/articles/s3#s3-setup

 

Using AWS S3 to Store Static Assets and File Uploads | Heroku Dev Center

Last updated May 27, 2020 Amazon Simple Storage Service (S3) is a “highly durable and available store” that is ideal for storing application content such as media files, static assets, and user uploads. S3 allows you to offload the storage of static fi

devcenter.heroku.com

paulrohan.medium.com/file-upload-to-aws-s3-bucket-in-a-node-react-mongo-app-and-using-multer-72884322aada

 

위 블로그를 참고해서 아래와 같이 작성했다.(ACL, CORS 설정이 필수 였다.)

heroku settings >configuration variables> AWS_ACCESS_KEY_ID와 KEY, REGION, S3_BUCKET_NAME을 등록했다.

 

내가 원하는 방향은 client에서 upload api를 호출하면 sever에선 AWS S3에 저장되고 저장된 결과값(req.file.location)을 다시 client에 전달하는 것이였다.

 

  const multer = require("multer");
  const multerS3 = require('multer-s3');
  const AWS = require("aws-sdk");

  const s3bucket = new AWS.S3({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: process.env.AWS_REGION
  });

  const upload = multer({
    storage: multerS3({
      s3: s3bucket,
      bucket: process.env.S3_BUCKET_NAME,
      key: function(req, file, cb){
        const fileName = file.originalname.toLowerCase().split(" ").join("-");
        cb(null, Date.now() + "-" + fileName);
      },
      acl: "public-read"
    })
  });

  app.post('/upload', upload.single("imageName"), (req, res, next) => {
    console.log(req.file)
    const returnData = {
      signedRequest: req.file,
      url: `https://${s3bucket}.s3.amazonaws.com/${req.file.location}`
    }
    res.write(JSON.stringify(returnData));
    res.end();
  });

 

'유통기한 관리_개인프로젝트' 카테고리의 다른 글

CORS for multiple origins  (0) 2021.04.20
배포하기  (0) 2021.04.12
Suspense가 뭔가요?  (0) 2021.04.08
CORS 처리  (0) 2021.04.02
mongoose '__v' 필드  (0) 2021.04.01