以文件流的方式导出文件-vueaxios

7次阅读

共计 805 个字符,预计需要花费 3 分钟才能阅读完成。

一般情况下, 后端会提供一个下载链接, 前端只需要使用 location.href 或者 a 标签打开链接即可.

当后端返回的是文件流时, 前端使用 blob 对象读取流并使用 a 标签下载.

axios({
       method: "get",
       url: this.downUrl,
       headers: {instuuid: sessionStorage.getItem("enterpriseUuid")
       },
       responseType: "blob" // 设置接收格式为 blob 格式
     }).then(res => {console.log("res :>>", res);
       const content = res.data;
       const blob = new Blob([content]); // 构造一个 blob 对象来处理数据
       const fileName = "企业级条件项库.xlsx";

       // 对于 <a> 标签,只有 Firefox 和 Chrome(内核)支持 download 属性
       //IE10 以上支持 blob 但是依然不支持 download
       if ("download" in document.createElement("a")) {
         // 支持 a 标签 download 的浏览器
         const link = document.createElement("a"); // 创建 a 标签
         link.download = fileName; // a 标签添加属性
         link.style.display = "none";
         link.href = URL.createObjectURL(blob);
         document.body.appendChild(link);
         link.click(); // 执行下载
         URL.revokeObjectURL(link.href); // 释放 url
         document.body.removeChild(link); // 释放标签
       } else {
         // 其他浏览器
         navigator.msSaveBlob(blob, fileName);
       }
     });
正文完
 0