관련지식
node.js, multer
multer
패키지를 이용해서 파일 업로드를 구현했다면 업로드 설정별로 최대 업로드 용량을 다르게 제한할수 있습니다. 예를들어 nginx
에서는 100MB로 설정하고 공지사항 쪽 업로드는 3MB로 제한, 자료실쪽 업로드는 100MB로 제한할수 있는것이죠. nginx
는 세세한 설정이 어려우므로 전체에 대해 최대 용량으로 고정하고 multer
에서 용량을 다시 제한하는것이 좋습니다.
방법은 간단합니다.
const storage = multer.diskStorage({
destination: function (req, file, cb) {
...
},
filename: function (req, file, cb) {
...
}
});
let upload = multer({
storage:storage
});
위와 같은 코드가 있다면 한줄만 추가하면 됩니다.
let upload = multer({
storage:storage,
limits: { fileSize: 1024 * 1024 } //1MB로 제한
});
이제 용량이 1MB 넘는 파일을 업로드하려고 하면 오류가 날텐데, 업로드 오류가 발생시 특별한 처리가 필요할수 있습니다. 만약 express.js
의 미들웨어 설정으로 업로드 기능을 적용했다면 에러 캐치가 안되므로 직접 호출하는 형태로 수정해야 합니다. 아래 코드는 공식 가이드에서 가져온 것입니다. upload
변수가 무엇을 가리키는지만 주의해서 보시면 수정이 어렵지 않으실겁니다.
미들웨어 설정)
var upload = multer()
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
})
직접 호출)
var upload = multer().single('avatar')
app.post('/profile', function (req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
} else if (err) {
// An unknown error occurred when uploading.
}
// Everything went fine.
})
})
'node.js' 카테고리의 다른 글
[node.js] 중국어 -> 병음 변환을 위한 패키지 (0) | 2020.01.23 |
---|---|
[node.js] JavaScript heap out of memory (0) | 2020.01.10 |
[node.js] 구글 이미지 검색 만들기(no api) (1) | 2019.12.12 |
[node.js] sqlite3 패키지를 node v10 에서 사용하기 (0) | 2019.10.25 |
[node.js] 인스타그램 사용을 위한 instagram-web-api2 패키지 써보기 (0) | 2019.10.21 |