스터디코딩

[node.js / s3] node 백엔드에서 s3로 이미지 업로드(multer) 본문

nodejs

[node.js / s3] node 백엔드에서 s3로 이미지 업로드(multer)

퓨처디벨로퍼 2022. 2. 17. 06:24

1. multer 라이브러리

- 익스프레스 서버에서 이미지를 수신하고 세 줄의 코드처럼 작성하여 파일 시스템에 저장할 수 있습니다.

 - express에서 파일 업로드를 수행 및 처리하기 위해 외부 패키지를 설치해야한다. 그래야 multipart/form-data를 처리할 수 있게된다.

 - 파일 업로드를 위해 사용되는 multipart/form-data를 다루기 위한 nodejs의 미들웨어입니다. 

설치

$ npm install --save multer

 

2. 이미지를 서버에 저장하기

server.js

const multer  = require('multer')
const upload = multer({ dest: 'uploads/' }) //내 서버에 업로는되는 파일의 대상 위치

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

- upload.single('avatar') 파일을 수락하는 미들웨어 기능을 만들어준다.

 

- 게시물 요청이 이루어 지면 multer가 avatar 이미지 바이너리 데이터를 확인하고 uploasds 폴더에 저장

- filename을 database에 저장한다.

3. 서버에서 s3 저장하기

 

3-1. AWS SDK

- AWS를 프로그래밍적으로 제어하는데는 많은 노력이 필요하다. 이 중에서 반복되고, 재활용 가능한 부분을 AWS 측에서 미리 개발해서 제공하고, 개발자들은 자신들의 비즈니스에 집중할 수 있도록 미리 만들어져서 제공되는 도구들의 집합이 AWS SDK이다.

- 설치

npm install aws-sdk

 

 

 

3-2. s3.js

 

require('dotenv').config()
const S3 = require('aws-sdk/clients/s3') //aws-sdk에서 s3부분 사용


//.env 파일 생성 후 
const bucketName = process.env.AWS_BUCKET_NAME
const region =  process.env.AWS_BUCKET_REGION
const accessKeyId =  process.env.AWS_BUCKET_ACESS_KEY
const secretAccessKey =  process.env.AWS_BUCKET_SECRET_KEY

const s3 = new S3({
  region,
  accessKeyId,
  secretAccessKey
})

// uploads a file to s3
function uploadFile(file) {
  const fileStream = fs.createReadStream(file.path)

  const uploadParams = {
    Bucket: bucketName,
    Body: fileStream,
    Key: file.filename
  }

  return s3.upload(uploadParams).promise()
  //콜백함수를 사용하는 대신 반환위해 promise() 함수 호출
}
exports.uploadFile = uploadFile


// downloads a file from s3
function getFileStream(fileKey) {
  const downloadParams = {
    Key: fileKey,
    Bucket: bucketName
  }

  return s3.getObject(downloadParams).createReadStream()
}

 

 

3-3. dotenv 설치

API 키나 계정의 ID, 비밀번호와 같은 기밀 정보를 있는 그대로 코드에 작성하거나,
기밀 정보가 담긴 코드를 Github과 같은 오픈소스에 공개하는 것은 보안적으로 아주 위험한 행동이다.

dotenv .env라는 외부 파일에 중요한 정보를 환경변수로 저장하여 정보를 관리할 수 있게 해준다.
그래서 dotenv를 사용하면, 전역적으로 필요한 정보나 기밀 정보와 같이 예민한 정보를
일반 소스 코드 내부가 아닌 .env라는 외부 파일에 작성할 수 있게 된다.

잊지 말아야할 것(!)은 중요한 정보가 담긴 .env파일을 git에 commit하면
파일 내용이 그대로 git에 박제(?) 되기 때문에
.gitignore에 .env 파일을 추가해주어 파일이 git에 올라가지 않도록 배제해준다.

 

-설치

npm i dotenv

 

3-4. server.js

const { uploadFile, getFileStream } = require('./s3')
pp.post('/images', upload.single('image'), async(req, res) => {
  const file = req.file;
  const result = await uploadFile(file)
})

 

4. 서버에서 사진파일 삭제하기

- s3에 저장했기 때문에.

server.js

const fs = require('fs')
const util = require('util')
const unlinkFile = util.promisify(fs.unlink)

pp.post('/images', upload.single('image'), async(req, res) => {
  const file = req.file;
  const result = await uploadFile(file)
 
 //파일 삭제
  await unlinkFile(file.path)

});

 

*multer-s3 VS 위의 방식

multer-s3

서버자체에 저장하지 않고 바로 s3에 저장해줌.

바로 보내려는 경우 편리하다.

위의 방식

필터 적용과 같은 몇가지 작업을 수행할 수 있다. 

app.post('/images', upload.single('image'), async(req, res) => {
   const file = req.file;
   const result = await uploadFile(file)
   await unlinkFile(file.path)

  // apply filter
  // resize

})

 

 

'nodejs' 카테고리의 다른 글

[node.js/express] 라우터 분리하기  (0) 2021.12.05
[Node.js] Request param,query, body 의 차이점  (0) 2021.12.04
[Express]  (0) 2021.12.02
Nodejs에서 동기와 비동기 1  (0) 2021.11.28
javascript 3  (0) 2021.11.28
Comments