더북(TheBook)

먼저 파일을 하나만 업로드하는 경우(multipart.html과 같은 경우)에는 single 미들웨어를 사용합니다.

app.post('/upload', upload.single('image'), (req, res) => {
  console.log(req.file, req.body);
  res.send('ok');
});

single 미들웨어를 라우터 미들웨어 앞에 넣어두면, 멀터 설정에 따라 파일을 업로드한 후 req.file 객체가 생성됩니다. 인수는 input 태그의 name이나 폼 데이터의 키와 일치하게 넣으면 됩니다. 업로드 결과는 req.file 객체 안에 들어 있으며, req.body에는 파일이 아닌 데이터인 title이 들어 있습니다.

req.file 객체는 다음과 같이 생겼습니다.

{ 
  fieldname: 'image',
  originalname: 'nodejs.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: 'uploads/',
  filename: 'nodejs1514197844339.png',
  path: 'uploads\\nodejs1514197844339.png',
  size: 53357
}