html
<h4 class="text-center mt-3">업로드페이지</h4>
<div class="container mt-4 upload-background">
<form enctype="multipart/form-data" class="mt-5">
<input type="file" name="profile">
<button type="button" class="btn btn-danger" onclick="fileUpload()">업로드</button>
</form>
</div>
javascript
function fileUpload() {
let file = new FormData($('form').get(0)) // form 태그를 들고옴
$.ajax({
type : 'POST',
url : '/upload',
data : file,
dataType : 'json',
processData : false,
contentType : false,
success : function(response) {
alert(response.message)
window.location.reload()
},
error : function(response) {
}
})
}
ajax로 form 전송을 가능하게 해주는 FormData 객체
file 이라는 인스턴스를 생성
html 내에 form 태그를 전부 불러온다, 0번째 form태그를
( $('form').get(0) )
const multer = require('multer')
let storage = multer.diskStorage({
destination : (req, file, cb) => {
cb(null, './public/image')
},
filename : (req, file, cb) => {
cb(null, file.originalname)
}
})
let upload = multer({storage : storage})
module.exports = upload
app.get('/upload', (req, res) => {
res.render('upload.ejs')
})
app.post('/upload', upload.single('profile'), (req, res) => { // multer가 원래 미들웨어
res.status(200).json({message : '업로드 완료'})
})
app.get('/upload/:imageName', (req, res) => {
const {imageName} = req.params
res.sendFile(__dirname + '/public/image/' + imageName)
})