- 파일업로드 경로와 파일 이름 설정
// utils/fileUpload.js const multer =require('multer') const path =require('path')
let storage = multer.diskStorage({
destination: (req, file, callback) => { // 파일 업로드 경로
callback(null, path.join( _dirname, '../../uploads' ));
},
filename: (req, file, callback) => { // 파일 이름 설정
callback(null, file.originalname + '' + new Date().getTime());
}
});
module.exports = multer({storage});
// s3같은 곳에 업로드해서 메모리로 저장할때는 multer({storage: memoryStorage()});
- form에 encType 지정하고 file에 name을 지정
```html
<form method="POST" encType="multipart/form-data" action="http://localhost:3333/upload">
<input type="file" name="img" />
<button type="submit" >등록하기</button>
</form>
- file.메서드를 호출, 1개 업로드는 single(), 멀티파일 업로드는 array() , input 여러개는 fields()
- 'file_name'은 input file의 name
- file.single(file_name');
- file.array(file_name'), 업로드제한할갯수);
- file.fields({name: 'file_name1', maxCount: 업로드제한할갯수},{name: 'file_name2', maxCount: 업로드제한할갯수})
const file = require('../utils/fileUpload');
router.post('/books/registry', file.single('img'), (req, res, next)=>{
console.log(req.file);
res.status(201).json({message: 'succeess'});
});
- req.file 내용
```json
{
fieldname: 'img',
originalname: 'logo.png',
encoding: '7bit',
mimetype: 'image/png',
destination: '업로드경로',
filename: 'logo_1581347076837.png',
path: '업로드경로/logo_1581347076837.png',
size: 1684
}
'Backend > Node.js' 카테고리의 다른 글
[작성중]세션과 토큰 그리고 JWP (0) | 2020.03.16 |
---|---|
[가비아] Node.js 웹호스팅 세팅 (0) | 2020.01.27 |
[NVM] Node.js 설치 (0) | 2020.01.23 |
[graphQL] rest API와 차이점, Apollo Server로 맛보기 (0) | 2020.01.10 |
Error handling과 custom Error 생성 (0) | 2020.01.02 |