index.js 文件
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const { multer } = require('./model/multer');
const app = express();
app.use(express.static('static'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// 单文件处理
app.post('/upload', multer().single('img'), (req, res, next) => {
var body = req.body;
console.log(req);
const basename = path.basename(req.file.path)
res.send({
body: req.body,
file: req.file
});
})
// 多文件处理
const cpUpload = multer().fields([{ name: 'img1', maxCount: 1 }, { name: 'img2', maxCount: 8 }]);
app.post('/uploads', cpUpload, (req, res) => {
res.send({
body: req.body,
files: req.files
});
})
app.listen(3001, () => {
console.log('服务运行与3001端口');
})
multer 文件
const multer = require('multer');
const path = require('path');
const mkdirp = require('mkdirp')
const sd = require('silly-datetime');
module.exports = {
multer() {
// 存储对象
var storage = multer.diskStorage({
destination: function (req, file, cb) {
const date = sd.format(Date.now(), "YYYY-MM-DD");
const dir = path.join('static/upload', date);
new Promise((resolve, reject) => {
mkdirp(dir);
resolve();
}).then(() => {
cb(null, dir);
}).catch(err => {
console.log('创建上传目录失败:' + err.message);
})
},
// 修改上传文件名
filename: function (req, file, cb) {
// 获取原来上传文件的后缀名
const extname = path.extname(file.originalname);
cb(null, Date.now() + extname)
}
});
const upload = multer({
storage: storage
});
return upload;
}
}