Fetch 上传 FormData 为什么解析失败?检查 Content-Type 的 boundary

作者:小满时间:2026-12-01浏览:346

对比 Fetch 上传 FormData 时显式与自动设置 Content-Type 的结果,用本地 Request 检查 multipart 分隔符,并修复统一请求封装里的默认头。

上传附件失败时,Network 面板里可能照样能看到请求体。先看一下实际发出的 Content-Type。如果里面只有 multipart/form-data,解析器知道这是一份表单,却拿不到用来分隔各个字段的 boundary。

用两份 Request 复现问题

用同一份 FormData 构造两个 Request,其中一个手动指定 Content-Type。先从请求副本读取正文首行,再对原请求调用 formData()。这里用 clone() 是因为同一份请求体只能读取一次。整段代码只构造和解析请求,整个过程都在浏览器内完成。

async function compareUploads() {
  const form = new FormData();
  form.append('title', 'release notes');
  form.append(
    'attachment',
    new File(['draft'], 'notes.txt', { type: 'text/plain' }),
  );

  const url = new URL('/api/uploads', window.location.origin);
  const manual = new Request(url, {
    method: 'POST',
    headers: { 'Content-Type': 'multipart/form-data' },
    body: form,
  });
  const automatic = new Request(url, { method: 'POST', body: form });

  for (const [label, request] of [['manual', manual], ['auto', automatic]]) {
    const type = request.headers.get('content-type');
    const body = await request.clone().text();
    const firstLine = body.slice(0, body.indexOf('\r\n'));
    const boundary = type.includes('boundary=')
      ? type.split('boundary=')[1]
      : '';

    console.log(label, 'header has boundary:', Boolean(boundary));
    console.log(label, 'body has delimiter:', firstLine.startsWith('--'));
    if (boundary) {
      console.log(label, 'delimiter matches:', firstLine === '--' + boundary);
    }

    try {
      const parsed = await request.formData();
      console.log(label, 'attachment:', parsed.get('attachment').name);
    } catch (error) {
      console.log(label, 'parse error:', error.name);
    }
  }
}

compareUploads().catch(console.error);
手动设置请求头时,预期输出显示头中无 boundary、请求体有分隔线,解析时报 TypeError
预期控制台输出。手动声明类型以后,头里没有分隔符参数。

手动设置请求头后,浏览器照样会生成 multipart 请求体,所以 body has delimiter 显示 true。请求头缺了 boundary,浏览器里的 formData() 会以 TypeError 拒绝。真实上传时看到的状态码和报错由后端决定。

头和请求体要使用同一个分隔符

浏览器编码 FormData 时会为请求体生成一个分隔符。每个字段前的分隔线以两个连字符开头,后面紧跟这个值。没有预设 Content-Type 时,浏览器会把同一个值填进请求头的 boundary 参数。

头部 boundary 等于 B,请求体以两个连字符加 B 分隔字段,结束线另加两个连字符
用 B 代表实际生成的分隔符值。头部和每条分隔线都使用该值。

第二组里,delimiter matches 显示 true,解析结果也取到了附件名 notes.txt。分隔符由浏览器生成,排查时只需要比较同一份请求的头和请求体。

自动生成头时,预期输出显示 boundary 存在、与分隔线匹配,且成功解析 notes.txt
预期控制台输出。头里的 boundary 和请求体的分隔线对应,附件成功读出。

在上传入口去掉继承来的默认头

通用请求封装里常有一个默认的 application/json 请求头。如果上传分支继承了它,可以先复制默认头,再删除 Content-Type。直接把 FormData 交给 fetch(),浏览器就能补上带分隔符的请求头,认证头等其他配置也会保留。

async function sendUpload(form, defaultHeaders) {
  const headers = new Headers(defaultHeaders);
  headers.delete('content-type');

  const response = await fetch('/api/uploads', {
    method: 'POST',
    headers,
    body: form,
  });
  if (!response.ok) {
    throw new Error(`Upload failed: ${response.status}`);
  }
  return response;
}

把示例中的 /api/uploads 换成项目的上传路由。如果实际请求头已经带了正确的 boundary,接下来检查后端有没有启用 multipart 解析,以及接收文件的字段名是不是 attachment。

作者最新文章
相关文章
更多