//文件上传测试
const express = require('express');
const router = express.Router();
const fs = require('fs');
const multer = require('multer');
let path = require("path");
function uploadConfig(folder, mb, suffix) {
// folder:上传文件的具体分类(具体文件夹名字)
// mb:上传文件的大小限制(KB)
// suffix:上传文件的类型控制(数组)
path_new = path.resolve(__dirname, '../public/uploads/' + folder);
return multer({
storage: multer.diskStorage({
//文件存储位置
destination: (req, file, cb) => {
fs.mkdir(path_new, { recursive: true }, (err) => {
if (err) throw err;
});
cb(null, path_new);
},
//文件名
filename: (req, file, cb) => {
cb(null, `${Date.now()}_${Math.ceil(Math.random() * 1000)}_multer.${file.originalname.split('.').pop()}`);
}
}),
limits: {
//上传文件的大小限制,单位bytes
fileSize: 1024 * 1024 * mb
},
fileFilter: (req, file, cb) => {
//文件类型
if (suffix.indexOf(file.mimetype) !== -1) {
cb(null, true);
} else {
cb(null, false);
}
}
}).any();
}
router.post('/upload/img', uploadConfig('images/', 10, ['image/jpeg', 'image/jpg']), async function (req, res, next) {
let uploadFile = req.files;
if (uploadFile.length == 0) {
res.json({ code: 233, info: '文件上传错误' });
} else {
res.json({ code: 200, info: `文件上传成功数量:${uploadFile.length}`, mes: uploadFile });
}
});
module.exports = router;
网友评论