Bootstrap

前端下载后端返回的二进制文件流

download = (url, params) => {
    let filename;
    window.fetch(url, {
      method: 'POST',
      body: JSON.stringify(params),
      "Access-Control-Allow-Origin" : "*",
      "Access-Control-Allow-Credentials" : true,
      header: {
         'Content-Type': 'application/json;charset=UTF-8'
      }
    }).then(function(response) {
      // 获取文件名
      response.headers.forEach((val, key) => {
        if(key === 'content-disposition'){
          filename = val.split(";")[1].split("filename=")[1];
        }
      }); 
      return response.blob();
    }).then(function(blob) {
      const link = document.createElement('a');
      link.style.display = 'none';
      let URL = window.URL || window.webkitURL;
      link.href = URL.createObjectURL(blob);
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      // 释放的 URL 对象以及移除 a 标签
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    });
  };

 

;