Fetch上传文件(不须要设置headers)

Fetch上传文件(不须要设置headers)

最近在项目中有一个上传文件的需求,而后我使用了fetch进行文件上传, 代码以下:javascript

<!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>
复制代码

运行结果:html

code: 9999
data: []
msg: "文件不存在"
time: 1546948790.707762
复制代码

咱们查看一下Request Headerjava

Content-Type: multipart/form-data
复制代码

能够看出这个地方的content-Type已经设置为了multipart/form-data 可是为何会报文件不存在呢? 再看看咱们的formDatajson

------WebKitFormBoundary8RVZAoLHNvQ5pKqL
Content-Disposition: form-data; name="file"; filename="20180717133748_52656.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet


------WebKitFormBoundary8RVZAoLHNvQ5pKqL--
复制代码

这里能够明显看出这个文件是存在'------WebKitFormBoundary8RVZAoLHNvQ5pKqL--'做为分隔的,那这个地方就上下没有达到一致。bash

boundary的重要性

在rfc1867协议中规定,咱们在指定content-type为multipart/form-data时,代表咱们须要传递的是多媒体内容,咱们须要指定boundary【分隔符】来分割当上传多个文件/图片。boundary是随机生成的数字和字母的组合。微信

按照上面的写法能够看出,Request Header里面的content-type中只是设置了multipart/form-data,而没有随机生成的boundary值,app

使用fetch上传文件遇到的坑

咱们都知道在上传多媒体文件的时候,咱们是须要指定Content-Type的,可是通过小编的测试,把代码经过以下修改:post

<!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
复制代码

再看看formDatafetch

------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。若是你知道缘由能够留言喔。期待你的精彩答复。

欢迎关注微信公众号

相关文章
相关标签/搜索