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

Node.js读取FormData中Excel文件报错,请求排查代码问题

问题分析与解决

核心错误原因

你在控制器中调用excelToJson时参数使用错误:

  • convert-excel-to-json的*sourceFile*参数仅支持文件路径字符串,而你传入了file.buffer(Buffer对象),导致包内部尝试将其作为路径处理时类型不匹配,抛出ERR_INVALID_ARG_TYPE错误。

修复步骤

1. 修正后端控制器的excelToJson调用

将sourceFile替换为*source*字段,传入Buffer对象:

const excelToJson = require('convert-excel-to-json');

exports.generalExcelImport = async function(req, res) {
  const file = req.files[0];
  
  console.log({ file: file});

  // 替换sourceFile为source,传入buffer
  const jsonData = excelToJson({ source: file.buffer });
  return res.status(200).send({ data: jsonData, message: 'Imported successfully' });  
}

2. 优化前端axios请求(可选但推荐)

前端手动设置Content-Type: multipart/form-data会导致axios无法自动添加正确的boundary分隔符,可能引发后端解析异常。删除手动设置的Content-Type,让axios自动处理:

let formData = new FormData(), headers = {};

// 移除手动设置的Content-Type,交由axios自动处理
// headers['Content-Type'] = 'multipart/form-data';
headers['Accept'] = 'application/json';

formData.append('dataFile', file);

let res = await axios({
    method: 'POST',
    headers,
    url: '/api/products/general-excel-import',
    data: formData
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 16:09:45