Fetch上传文件(不需要设置headers)
最近在项目中有一个上传文件的需求,然后我使用了fetch进行文件上传, 代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试fetch上传文件</title>
</head>
<body>
<input type="file" id="files" onchange="upload(event)"/>
<script type="text/javascript">
function upload(event) {
const formData = new FormData();
formData.append('file', event.target.files[0]);
fetch('/upload', {
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData,
}).then(response => response.json())
.then((data) => {
console.log(data);
});
}
</script>
</body>
</html>
复制代码
运行结果:
code: 9999
data: []
msg: "文件不存在"
time: 1546948790.707762
复制代码
我们查看一下Request Header
Content-Type: multipart/form-data
复制代码
可以看出这个地方的content-Type已经设置为了multipart/form-data 但是为什么会报文件不存在呢? 再看看我们的formData
------WebKitFormBoundary8RVZAoLHNvQ5pKqL
Content-Disposition: form-data; name="file"; filename="20180717133748_52656.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
------WebKitFormBoundary8RVZAoLHNvQ5pKqL--
复制代码
这里可以明显看出这个文件是存在'------WebKitFormBoundary8RVZAoLHNvQ5pKqL--'作为分隔的,那这个地方就上下没有达到一致。
boundary的重要性
在rfc1867协议中规定,我们在指定content-type为multipart/form-data时,表明我们需要传递的是多媒体内容,我们需要指定boundary【分隔符】来分割当上传多个文件/图片。boundary是随机生成的数字和字母的组合。
按照上面的写法可以看出,Request Header里面的content-type中只是设置了multipart/form-data,而没有随机生成的boundary值,
使用fetch上传文件遇到的坑
我们都知道在上传多媒体文件的时候,我们是需要指定Content-Type的,但是经过小编的测试,把代码通过如下修改:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试fetch上传文件</title>
</head>
<body>
<input type="file" id="files" onchange="upload(event)"/>
<script type="text/javascript">
function upload(event) {
const formData = new FormData();
formData.append('file', event.target.files[0]);
fetch('/upload', {
method: 'post',
body: formData,
}).then(response => response.json())
.then((data) => {
console.log(data);
});
}
</script>
</body>
</html>
复制代码
也就是把header去掉,不指定Content-Type; Request Header中的Content-Type就默认设置为了multipart/form-data;
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarythLhwaT87w2PJrYz
复制代码
再看看formData
------WebKitFormBoundarythLhwaT87w2PJrYz
Content-Disposition: form-data; name="file"; filename="20180717133748_52656.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
------WebKitFormBoundarythLhwaT87w2PJrYz--
复制代码
可以看出formDat里的数据boundary和Request Header里的boundary是一致的。 运行代码的结果结果就是可以正常的上传文件了,为什么呢? 在使用fetch上传文件的时候为什么不需要设置Content-Type,在我们进行上传多媒体文件的时候就默认设置成了multipart/form-data。
为什么Fetch上传文件时不需要设置headers。如果你知道原因可以留言喔。期待你的精彩答复。
欢迎关注微信公众号