출처 : https://www.npmjs.com/package/multer
게시판에 사진을 넣는 걸 만들어보고 싶어서 검색하다가 찾았다.
Multer는 파일 업로드를 위해 사용되는 multipart/form-data를 다루기 위한 node.js의 미들웨어
터미널 입력
npm install multer
const multer = require('multer')
const path = require('path')
// 어느 폴더안에 업로드 한 파일을 저장할 지 결정
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/images/')
},
// 폴더 안에 저장되는 파일 명을 결정하는 데 사용
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now()+path.extname(file.originalname));
}
})
file.fieldname = 폼에 정의된 필드명 (나는 img)
path.extname(file.originalname)
-> path.extname(a)
= 파라미터의 확장자를 리턴한다.
= file.originalname = 사용자가 업로드한 파일명
// 업로드 제어 파일이 저장될 위치는 위에서 설정한 storage다.
const upload = multer({ storage: storage });
우리가 지정한 경로에, 우리가 지정한 이름으로 잘 들어가 있다.
이 부분(enctype="multipart/form-data")을 html에 꼭 입력해야 한다.
<form action='/board/write'
method='post'
enctype="multipart/form-data">
모든게 정상적으로 작동한다면 다음과 같이 보여질 수 있다.