node+express使用multer实现文件上传修改上传路径文件重命名

本文介绍了如何在Electron项目中使用Express和multer中间件处理图片或视频上传,包括设置文件存储路径、类型检查和错误处理,以及如何在其他路由中调用这个上传功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自己的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;
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值