fetch 上传文件 FormData 失败原因

用 fetch 通过 post 上传文件,发现服务器那边获取不到参数,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const formData = new FormData();
formData.append('tid', id);
formData.append('file', file);

fetch(`${api}/lot`, {
method: 'POST',
headers: {
'Content-type': 'multipart/form-data;'
},
body: formData
})
.then((response) => response.json())
.then((response) => {
console.log(response)
});

然后测试发现,如果直接用 HTML 表单的方式是可以的。看了下浏览器的提交详情,对比发现我用 fetch 上传,header 的 Content-Type 字段是这样的:

1
Content-Type: multipart/form-data;

而用原生表单提交则是:

1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryoTb4kZI011bOGyNt

解决方法

网上查了,fetch 时把 Content-Type 留空即可,测试可行。

参考资料