[Node.js] multer 미들웨어

으나·2023년 11월 9일
0

NodeJS

목록 보기
3/4
post-thumbnail

1. 멀티파트 데이터 형식 (multer)

form 태그의 enctype이 multipart/form-data인 경우다.

  • 멀티 데이터 형식이기 때문에 bodyparser로는 요청 본문을 해석할 수 없다.
  • multer 패키지가 필요하다

2. multer 설정하기

multer 함수를 호출한다.

  • storage는 저장할 공간에 대한 정보다.
    -> diskStorage는 하드디스크에 업로드 파일을 저장한다는 것이다.
  • destination은 저장할 경로를 done의 두번째 인수로 넘기면 된다.
  • filename은 저장할 파일명(파일명+날짜+확장자 형식)을 done으로 넘기면 된다.
  • limits는 파일 개수나 파일 사이즈를 제한할 수 있다.
const multer = require('multer');

const upload = multer({
    storage: multer.diskStorage({
        destination(req, file, done) {
            done(null, 'uploads/');
        },
        filename(req, file, done) {
            const ext = path.extname(file.originalname);
            done(null, path.basename(file.originalname, ext) + Date.now() + ext);
        },
    }),
    limits: { fileSize: 5 * 1024 * 1024 },
});

3. multer 미들웨어들

single과 none, array, fields 미들웨어 존재

  • single은 하나의 파일을 업로드할 때, none은 팡리을 아예 업로드하지 않을 때 사용한다.
  • req.file안에 업로드 정보를 저장한다.
  • array와 fields는 여러 개의 파일을 업로드 할 때 사용한다.
  • array는 하나의 요청 body 이름 아래 여러 파일이 있는 경우 사용한다.
  • fields는 여러 개의 요청 body이름 아래 파일이 하나씩 있는 경우 사용한다.
  • 두 경우 모두 업로드된 이미지 정보가 req.files 아래에 존재한다.
app.post('/upload', upload.single('image'), (req, res) => {
    console.log(req.file, req.body);
    res.send('ok');
}); // 하나의 파일을 업로드함

app.post('/upload', upload.none(), (req, res) => {
    console.log(req.body);
    res.send('ok');
}); // 아예 업로드 하지 않음

app.post('/upload', upload.array('many'), (req, res) => {
    console.log(req.files, req.body);
    res.send('ok');
}); // 하나의 요청 body 이름 아래 여러 파일이 있는 경우

app.post('/upload',
    upload.fields([{ name: 'image1' }, { name: 'image2' }]),
    (req, res) => {
        console.log(req.files, req.body);
        res.send('ok');
    },
); //여러 개의 요청 body이름 아래 파일이 하나씩 있는 경우
profile
Node.js 공부중 ._.

0개의 댓글