서비스를 제공하는 웹애플리케이션에서 사용자가 이미지파일을 등록하여 서비스를 제공하기 위해서는 이미지 파일을 불러와서 서버에 저장해야 합니다.
express와 multer를 이용하여 이미지 파일의 정보를 파싱하여 저장하는 방법에 대해 알아보겠습니다.
1. multer 란?
multer 는 파일 업로드를 위해 사용되는 multipart/form-data를 다루기 위한 node.js의 미들웨어 입니다. 효율성을 최대화 하기 위해 busboy를 기반으로 하고 있습니다.
https://github.com/mscdex/busboy
2. multer 설치하기
$npm install multer
multer는 body객체와 한 개 file또는 여러 개의 files객체를 request 객체에 추가합니다. body객체는 폼 텍스트 필드의 값을 포함하고, 한 개 또는 여러 개의 파일은 폼을 통해 업로드된 파일을 포함하고 있습니다.
예시) 폼 태그 작성, enctype에 multipart/form-data 를 지정
<form action="/profile" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" />
</form>
multer를 불러오고, upload를 할 경로를 지정합니다.
파일을 등록하기 위해 post 메소드로 한 개 파일은 upload.single, 여러 개 파일은 upload.array를 사용하고 input의 name에 해당되는 값을 같이 사용합니다.
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express()
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
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
3. 이미지 파일 등록하기(예제)
신규 캠핑장 등록하는 화면에서 캠핑장 사진(screen.png)을 아래와 같이 등록합니다.
등록 폼을 통해 전달되는 데이터는 다음과 같습니다. req.body, req.file
console.log 로 body 내용과 file 정보를 아래와 같이 확인해 볼 수 있습니다.
[Object: null prototype] {
campground: [Object: null prototype] {
title: 'new mountain',
location: 'lakeside',
price: '12',
description: 'good place !!!'
}
} {
fieldname: 'image',
originalname: 'screen.png',
encoding: '7bit',
mimetype: 'image/png',
destination: 'uploads/',
filename: '365d7ce5bfdb6f61fcb96ae2d2db6b04',
path: 'uploads/365d7ce5bfdb6f61fcb96ae2d2db6b04',
size: 150280
}
수집하는 데이터 항목은 다음과 같습니다.
key | description | note |
fieldname | Field name specified in the form | |
originalname | Name of the file on the user's computer | |
encoding | Encoding type of the file | |
mimetype | Mime type of the file | |
size | Size of the file in bytes | |
destination | The folder to which the file has been saved | DiskStorage |
filename | The name of the file within the destination | DiskStorage |
path | The full path to the uploaded file | DiskStorage |
buffer | A Buffer of the entire file | MemoryStorage |
'자바스크립트(Javascript)' 카테고리의 다른 글
데이터 검색 화면 만들기(mongoDB) (0) | 2023.10.20 |
---|---|
Express 보안 - Helmet 사용하기 (0) | 2023.10.02 |
평점 표현 하기 - Starability 라이브러리 (0) | 2023.09.18 |
유효성 검증 - Joi (0) | 2023.09.02 |
bootstrap validation 폼(form) 태그에 적용하기 (0) | 2023.08.29 |