multer

multer?

node.js에서 파일을 업로드 하려면 multer모듈을 사용해 파일 업로드가 가능합니다. 파일 업로드를 도와주는 모듈이라고 생각하시면 됩니다.

기본환경 설정


위와 같이 파일, 폴더 환경을 구성합니다. uploads폴더는 업로드 된 파일이 저장되는 폴더입니다.

1
2
3
4
5
block content
form(action='/upload', method='post', enctype="multipart/form-data")
label
input(type='file', name='file', required)
button(type='submit') 업로드

index.pug파일을 위와 같은 코드로 작성하게 되면 다음과 같이 익스플로러에 표시됩니다.
enctype="multipart/form-data"과 같이 enctype을 설정해주어야 사용자가 전송한 파일을 서버로 전송 할 수 있습니다.

multer 설정

1
npm install multer --save

위 코드를 통해 multer를 설치합니다.

1
2
3
4
5
const express = require('express')
const multer = require('multer')
const upload = multer({
dest: 'uploads/'
})

multerrequire 해줍니다. uploadmulter를 통해 파일이 들어오면 저장될 위치를 설정하는 곳입니다. dest뒤 저장할 폴더를 설정합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
const PORT = 3003
const app = express()
app.set('view engine', 'pug')
app.get('/', (req, res) => {
res.render('index.pug')
})
app.post('/upload', upload.single('file'), (req, res) => {
console.log(req.file)
res.redirect('/')
})
app.listen(PORT, () => {
console.log(`listening ${PORT}...`)
})

pug를 사용하였기 때문에 app.set('view engine', 'pug')를 사용하여 셋팅하였습니다.


여기서 주의 할 점은 upload.single괄호()안 내용이 postname이랑 같아야합니다. 위 사진을 꼭 참고 바랍니다.
위와 같이 환경을 꾸며주게 되면 기본설정은 끝났습니다.
하지만 이렇게 설정해주면 작은(?)문제가 발생합니다.


위 사진과 같이 원본파일의 이름은 javascript.png파일이지만 저장되는 파일 이름은 a7ab2f0b7194e845b92d8f494b56d3ba로 알 수 없는 이름 그리고 확장자가 없어지게 됩니다.
확장자가 사라져 어떤 파일인지 알아볼 수 없긴 하지만 사진파일은 열 수 있습니다. 하지만 확장자를 지정해주려면 약간의 커스텀이 필요합니다.

multer 세부 설정

1
2
3
const upload = multer({
dest: 'uploads/'
})

이 업로드 부분을 수정하도록 하겠습니다.

1
2
3
4
5
6
7
8
9
const customStorage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
const upload = multer({ storage: customStorage })

upload로 설정된 변수를 위와 같이 변경하게 되면 파일을 업로드 할 때 원본의 이름 + 확장자가 저장됩니다. 여기서 파일 업로드 시 중복되게 된다면 filename 부분을 설정하면 됩니다.


코드 option에 따라 설정을 변경하였더니 a7ab2f0b7194e845b92d8f494b56d3ba와 같이 알 수 없는 이름으로 저장되었던 파일이 javascript.png 파일로 저장 할 수 있게 되었습니다.

업로드 크기 파일을 제한 할 수 있습니다.

1
const upload = multer({ storage: customStorage })

이렇게 선언된 upload 변수에 옵션을 넣어주면 됩니다.

1
2
3
4
5
const maxsize = 1024 * 1024 // 1mb
const upload = multer({
storage: storage,
limits: {fileSize: maxsize}
})

maxsize변수를 선언하고 limits 옵션을 사용하여 파일 사이즈를 custom 할 수 있습니다.

공유하기