Express 4.x中介軟體multer的使用
阿新 • • 發佈:2019-02-05
express4.x中上傳檔案的中介軟體
在上傳介面中新增multer
中介軟體
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
var dir = path.resolve(__dirname, '../public', 'photos')
cb(null, dir)
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
var upload = multer({ storage: storage })
single('filename')
此處的filename
為input
標籤的name
屬性的值。
router.post('/upload', upload.single('photoImage'), function (req, res, next) {
var img = req.file
var name = req.body.photoName || img.originalname
var mathes = /\/(.+)$/.exec(img.mimetype)
if (!name.includes(mathes[1 ])) {
name = name + '.' + mathes[1]
}
var newPath = path.resolve(__dirname, '../public', 'photos', name)
fs.rename(img.path, newPath, function (err) {
if (err) {
return next(err)
}
Photo.create({
name: name,
path: newPath
}, function(err) {
if (err) {
return next(err)
}
res.redirect('/photos/upload')
})
})
})