You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用express-fileUpload时出现mv is not a function错误求助

解决express-fileUpload中“mv is not a function”报错问题

问题根源

你调用el.mv()时出错,是因为el是base64格式的字符串,而不是express-fileupload解析后生成的带mv方法的文件对象。mv方法仅适用于该库处理的表单上传文件(如multipart/form-data提交的文件),对base64字符串无效。

解决方案:手动处理base64图片

针对localStorage存储的base64图片,需要手动转换为文件并写入磁盘,步骤如下:

  1. 引入Node.js内置的fs和path模块,用于文件操作和路径拼接
  2. 拆分base64字符串,提取图片格式和纯数据部分
  3. 将base64数据转换为Buffer
  4. 使用文件模块写入目标文件夹

修改后的代码

const fileUpload = require('express-fileupload');
const fs = require('fs');
const path = require('path');
app.use(fileUpload());

// ...

const productsJson = {
  properties: req.body.products,
};

// 提前创建目标目录(避免目录不存在报错)
const targetDir = path.join(__dirname, '../public/UserFolder');
fs.mkdirSync(targetDir, { recursive: true });

productsJson.properties.forEach((e) => {
  e.meshImgs.forEach((el, index) => {
    // 拆分base64字符串,分离元数据和图片数据
    const [metaPart, base64Data] = el.split(',');
    // 提取图片扩展名(如png/jpg)
    const imgExt = metaPart.match(/image\/(\w+)/)[1];
    // 生成唯一文件名,避免覆盖
    const fileName = `${Date.now()}-${index}.${imgExt}`;
    const targetPath = path.join(targetDir, fileName);

    // 将base64转为Buffer并写入文件
    fs.writeFile(targetPath, base64Data, 'base64', (err) => {
      if (err) {
        console.error('图片保存失败:', err);
        return;
      }
      console.log('图片保存成功:', targetPath);
    });
  });
});

额外提示

  • 用path.join拼接路径可避免因操作系统差异导致的路径错误
  • 加入时间戳生成文件名,防止不同图片因索引重复被覆盖
  • 若使用异步逻辑,可改用fs.promises.writeFile配合async/await优化代码结构

内容的提问来源于stack exchange,提问作者Mateja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 17:45:00