Fetch 上传 FormData 为什么解析失败?检查 Content-Type 的 boundary
对比 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);

手动设置请求头后,浏览器照样会生成 multipart 请求体,所以 body has delimiter 显示 true。请求头缺了 boundary,浏览器里的 formData() 会以 TypeError 拒绝。真实上传时看到的状态码和报错由后端决定。
头和请求体要使用同一个分隔符
浏览器编码 FormData 时会为请求体生成一个分隔符。每个字段前的分隔线以两个连字符开头,后面紧跟这个值。没有预设 Content-Type 时,浏览器会把同一个值填进请求头的 boundary 参数。

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

在上传入口去掉继承来的默认头
通用请求封装里常有一个默认的 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。
JS直接通过文件路径读取本地JSON为什么报错
2026-12-01
llama.cpp b12877 的 Loom 即时编译意味着什么
2026-12-01
n8n 2.50.5 预发布版的默认自愈与脱敏修复怎样理解
2026-12-01






