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

使用FormData+Fetch上传文件报错Multipart: Boundary not found的解决咨询

问题描述

我尝试通过发送POST请求向服务器上传文件,代码如下:

const files = [...e.dataTransfer.files];
const data = new FormData();
data.append('taskId', taskId);
data.append('file', files[0]);
const token = localStorage.getItem('token');
fetch(`${URL}file`, {
  method: 'POST',
  headers: {
    'content-type': 'multipart/form-data',
    Authorization: `Bearer ${token}`,
  },
  body: data,
})
  .then((res) => res.json())
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

请求返回错误:statusCode: 400, message: 'Multipart: Boundary not found', error: 'Bad Request'。我已尝试移除content-type请求头,但问题仍未解决,请问该如何修复这个请求?问题出在哪里?

解决方案
  • 问题根源:当手动设置content-type: multipart/form-data时,没有附带必要的boundary分隔符——浏览器原本会自动为FormData生成并添加包含boundary的完整Content-Type头,手动设置会覆盖这个自动行为,导致后端无法解析多部分表单数据。即使移除该头,可能存在缓存或代码逻辑干扰,导致请求头未正确生成。
  • 修复步骤:
    1. 彻底移除content-type配置,仅保留授权头,让浏览器自动处理表单数据的请求头:
      fetch(`${URL}file`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${token}`,
        },
        body: data,
      })
      
    2. 核对请求地址:确认${URL}file是否与后端接口路径一致(参考接口文档中的定义,确保路径、请求方法匹配)。
    3. 检查字段名一致性:确认FormData中的taskId和file字段名与后端接口要求完全匹配,可通过接口文档查看参数定义。
    4. 验证请求头:在浏览器控制台Network面板中查看实际发送的请求,确认Content-Type是否为multipart/form-data; boundary=----WebKitFormBoundaryxxxxxx格式,确保boundary已自动添加。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:25:14