관련지식
node.js, multer

multer 패키지를 이용해서 파일 업로드를 구현했다면 업로드 설정별로 최대 업로드 용량을 다르게 제한할수 있습니다. 예를들어 nginx에서는 100MB로 설정하고 공지사항 쪽 업로드는 3MB로 제한, 자료실쪽 업로드는 100MB로 제한할수 있는것이죠. nginx는 세세한 설정이 어려우므로 전체에 대해 최대 용량으로 고정하고 multer에서 용량을 다시 제한하는것이 좋습니다.

방법은 간단합니다.

  1. const storage = multer.diskStorage({
  2. destination: function (req, file, cb) {
  3. ...
  4. },
  5. filename: function (req, file, cb) {
  6. ...
  7. }
  8. });
  9. let upload = multer({
  10. storage:storage
  11. });

위와 같은 코드가 있다면 한줄만 추가하면 됩니다.

  1. let upload = multer({
  2. storage:storage,
  3. limits: { fileSize: 1024 * 1024 } //1MB로 제한
  4. });

이제 용량이 1MB 넘는 파일을 업로드하려고 하면 오류가 날텐데, 업로드 오류가 발생시 특별한 처리가 필요할수 있습니다. 만약 express.js의 미들웨어 설정으로 업로드 기능을 적용했다면 에러 캐치가 안되므로 직접 호출하는 형태로 수정해야 합니다. 아래 코드는 공식 가이드에서 가져온 것입니다. upload 변수가 무엇을 가리키는지만 주의해서 보시면 수정이 어렵지 않으실겁니다.

미들웨어 설정)

  1. var upload = multer()
  2. app.post('/profile', upload.single('avatar'), function (req, res, next) {
  3. // req.file is the `avatar` file
  4. // req.body will hold the text fields, if there were any
  5. })

직접 호출)

  1. var upload = multer().single('avatar')
  2. app.post('/profile', function (req, res) {
  3. upload(req, res, function (err) {
  4. if (err instanceof multer.MulterError) {
  5. // A Multer error occurred when uploading.
  6. } else if (err) {
  7. // An unknown error occurred when uploading.
  8. }
  9. // Everything went fine.
  10. })
  11. })