Javascript/nodejs

[Node.js] 파일 업로드 (multer, 예제)

뉴벡엔드 2023. 12. 30. 00:07

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

 

참고

multer/doc/README-ko.md at master · expressjs/multer · GitHub

 

 

 

 

upload.js

const path = require('path')
const multer = require('multer')

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/')
    },
    filename: function (req, file, cb) {
        let ext = path.extname(file.originalname)
        cb(null, Date.now() + ext)
    }
})

var upload = multer({
    storage: storage,
    fileFilter: function (req, file, callback) {
        if (
            file.mimetype == "image/png" || file.mimetype == "image/jpg"
        ) {
            callback(null, true) // 파일허용하려면 'true'
        } else {
            console.log('only jpg & png file supported! ')
            callback(null, false) // 파일 거부하려면 'false'
        }
    },
    limits: {
        fileSize: 1024 * 1024 * 2
    }
})

module.exports = upload
 

 

destination 옵션은 어느 폴더안에 업로드 한 파일을 저장할 지를 결정합니다.

주의 : destination 을 함수로 사용할 경우, 디렉토리를 생성해야 할 책임이 있습니다. 문자열이 전달될 때, multer는 해당 디렉토리가 생성되었는지 확인합니다.

 

filename 은 폴더안에 저장되는 파일 명을 결정하는데 사용됩니다. 만일 filename 이 주어지지 않는다면, 각각의 파일은 파일 확장자를 제외한 랜덤한 이름으로 지어질 것입니다.

 

fileFilter 어느 파일을 업로드 할지, 혹은 건너뛸지 제어할 수 있게 함수에 설정합니다.

파일허용 : callback(null, true)

파일거부 : callback(null, false)

 

limits 선택적 속성의 크기 제한을 지정하는 객체

 

 

router.js

const express       = require('express')
const router        = express.Router()
 
const upload                   = require('../middleware/upload')
 
router.post('/upload', upload.array('avatar[]'), EmployeeController.store)
 

module.exports = router
 

 

req.files 는  avatar[]' 라는 파일정보를 배열로 가지고 있음

 

반응형