自己的electron小项目中有一个需要上传图片或视频的地方,为了实现上传效果在express中使用multer中间件,文档上写的还是比较易懂的,按照文档的案例实现之后上传完成文件是没有后缀的,也无法打开,看文档有困难的同学可以看看下面我自己写的案例有详细注释
看看效果
multer文档
先下载好依赖包
npm install multer --save
创建multer.js
const express = require('express');
const multer = require('multer');
const fs = require("fs")
const MulterError = multer.MulterError;
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const date = new Date();
let filePathArr = ['uploads']//文件路径数组 最后用/拼接路径
filePathArr.push(req.body.type);//前端传来的参数 文件类型 用来分类存放
filePathArr.push(date.getFullYear());
filePathArr.push(date.getMonth()+1);
let filePath = filePathArr.join('/');
checkDirectorySync(filePathArr);//验证文件夹是否存在 不存在创建
cb(null, filePath)
},
filename: function (req, file, cb) {
let filename = Date.now()+getMathRandom(0,1000);//使用时间戳加随机数防止重名
let mimetype = getFileExtension(file.originalname);//获取文件后缀
cb(null, filename + mimetype);
}
})
const legalType = ['audio', 'video', 'images'];//合法参数
const mimeType = ['image/gif', 'image/jpeg','image/png', 'video/mp4','audio/mpeg','video/mpeg','video/x-msvideo','audio/x-mpeg'];//合法文件类型
//fileFilter 使用文件过滤器可以筛选那些文件可以上传
const fileFilter = (req, file, cb) => {
let { type } = req.body;
if(type && legalType.includes(type) && mimeType.includes(file.mimetype)){
cb(null, true)//true继续执行
}else{
//cb(null,false) //第一个参数不传 返回upload函数的err处理 可以自定义返回数据
//cb({name: 'string',message: '参数错误',stack:' 详细错误'},false)//第一个参数是错误对象 传了请求接口会报500错误拒绝请求 错误信息message
}
}
const multerObj = multer({ storage: storage, fileFilter });
module.exports = {
multerObj, MulterError
}
//获取文件后缀
function getFileExtension(filename) {
let mimetype = filename.split('.').pop();
mimetype = mimetype?'.'+mimetype :'';
return mimetype;
}
const getMathRandom = (min,max)=>{
min = Math.ceil(min);
max = Math.floor(max);
return (Math.floor(Math.random() * (max - min + 1)) + min).toString();
}
//一层层查询路径文件夹是否存在 不存在创建
const checkDirectorySync = (arr)=>{
let path = "";
for (const val of arr) {
path += val + '/';
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
}
}
在别的地方使用上传,需要实现多文件上传的看文档修改
const express = require("express");
const router = express.Router();
const {multerObj,MulterError} = require('./base/multer')
/**
* 上传
* @param {*} name 名称
* @param type 类型images/viedo/audio 默认images
* @param cate_id 分类
* @return JSON(path:文件路径)
*/
router.post('/uploadFiles',multerObj.single('file'), async(req, res, next)=>{
//...
let body = req.body;
upload(req, res, function (err) {
if (err instanceof MulterError) {
// 发生错误
console.log(err);
} else if (err) {
// 发生错误
console.log(err);
}
// 一切正常
console.log(body); //upload里面的req是没有前端传来的文本域数据的
console.log(req.file);
res.json({code:200,path:req.file.path})
})
})
module.exports = router;