单文件上传
<form action="/admin/nav/doAdd" method="post" enctype="multipart/form-data">
标题:<input type="text" name="title" id="title"><br><br>
图片:<input type="file" name="pic" id="pic"><br><br>
描述:<textarea name="desc" id="desc" cols="30" rows="10"></textarea><br><br>
<input type="submit" value="提交">
</form>
const express = require('express')
const tools = require('../../model/tools')
router.post('/doAdd', tools.multer().single('pic'), (req, res) => {
res.send({
body: req.body,
file: req.file
})
})
const multer = require('multer')
const path = require('path')
const sd = require('silly-datetime')
const mkdirp = require('mkdirp')
let tools = {
multer() {
var storage = multer.diskStorage({
destination: async (req, file, cb) => {
let day = sd.format(new Date(), 'YYYYMMDD')
let dir = path.join('static/upload', day)
await mkdirp(dir)
cb(null, dir)
},
filename: function (req, file, cb) {
let extname = path.extname(file.originalname)
cb(null, Date.now() + extname)
}
})
var upload = multer({ storage: storage })
return upload
},
md5() { }
}
module.exports = tools
多文件上传
const express = require('express')
const tools = require('../../model/tools')
var router = express.Router()
router.get('/', (req, res) => {
res.send('用户列表')
})
router.get('/add', (req, res) => {
res.render('admin/user/add')
})
let cpUpload = tools.multer().fields([{ name: 'pic1', maxCount: 1 }, { name: 'pic2', maxCount: 1 }])
router.post('/doAdd', cpUpload, (req, res) => {
res.send({
body: req.body,
files: req.files
})
})
module.exports = router