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

如何通过POST API发送Blob格式Excel/CSV文件?请求体为空问题解决

如何通过POST API发送Blob格式的Excel/CSV文件

你当前代码的问题核心是:JSON.stringify无法序列化Blob对象,当你把Blob类型的excelFile放进JSON里转成字符串后,file_upload字段会被转成空对象{},导致请求体里完全没有文件数据。

正确的文件上传方式是使用FormData构造请求体,因为文件上传需要遵循multipart/form-data格式,而非application/json。

修改后的代码

const Csvsubmit = (event) => {
    console.log("csv", excelFile);
    setLoadingcsv(true);

    // 创建FormData实例,专门用于封装文件和表单数据
    const formData = new FormData();
    // 添加文件,第一个参数要和后端接口的接收字段名完全一致(此处为file_upload)
    formData.append('file_upload', excelFile);
    // 添加其他普通字段
    formData.append('created_by', user.id);

    const requestOption = {
      method: "POST",
      // 不要手动设置Content-Type,浏览器会自动生成带边界标识的multipart/form-data头
      body: formData,
    };

    fetch(process.env.REACT_APP_BACKEND + subdomain + "/staff/csvupload/", requestOption)
      .then((res) => {
        setLoadingcsv(false);
        if (res.status === 201) {
          return res.json();
        } else if (res.status === 406) {
          console.log("文件格式不支持");
          throw new Error('格式错误');
        } else {
          return res.json();
        }
      })
      .then((json) => {
        console.log(json);
        setopenid(0);
      })
      .catch((error) => {
        console.log(error);
      });
};

关键注意点

  • FormData是浏览器专门为文件上传设计的对象,能正确处理Blob/File类型数据,自动封装成符合规范的请求体
  • 禁止手动设置Content-Type:浏览器会自动添加包含边界标识的请求头(比如multipart/form-data; boundary=----WebKitFormBoundaryxxx),手动设置会丢失边界,导致后端无法解析文件
  • 确保后端接口已配置支持接收multipart/form-data类型的请求,且接收字段名和你append时的名称一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 02:36:30