자바스크립트/Node Js
[nodeJS] multer를 이미지 업로드
RightHot
2019. 1. 29. 01:25
multer 이미지 업로드
npm i multer
html
이미지를 업로드하기 위해서는 form에 아래와같이 enctype 속성을 추가해야된다.
<form enctype="multipart/form-data"></form>
post.js
storage
multer.diskStorage : 로컬에 저장
destination(req, file, callback) : 파일 저장 경로 지정
filename(req, file, callback) : 파일 이름 지정
const express = require('express');
const multer = require('multer');
const path = require('path');
const router = express.Router();
const upload = multer({
storage: multer.diskStorage({
destination(req, file, cb){
cb(null, 'uploads/')
},
filename(req, file, cb){
// 확장자 추출
const ext = path.extname(file.originalname);
// 이름설정 (basename:확장자제외 파일명) + 현재시간 + 확장자
cb(null, path.basename(file.originalname, ext) + new Date().valueOf() + ext);
},
}),
limit: { fileSize: 5 * 1024 * 1024},
});
// ** multer가 form 안의 <input id='img' />를 찾는다
// single('필드의 id') : 이미지 하나(단일필드)
// array('필드의 id') : 이미지 여러개(단일필드)
// fields('필드의 id') : 이미지 여러개(여러필드)
// none('필드의 id') : 이미지가 아닐때
router.post('/img', upload.single('img'),(req,res)=>{
// 파일은 업로드 후 req.file에 저장되어있다.
console.log(req.file);
// 파일 이름을 다시 프론트로 보내준다
res.json({ url: `/img/${req.file.filename}`});
});
router.post('/');
module.exports = router;