在Vue中使用blob进行点击下载

今天来写一下如何在Vue的项目中用blob实现点击下载。
通常window.open可以满足一般的下载需求,但是当我们下载时需要带上请求头时,window.open就不能满足该需求,所以这时候就需要用到blob。话不多说直接上图。

axios({
        url: url,  //请求地址
        method: "GET", //请求方法
        responseType: "blob" //请求类型为blob
      }).then(res => {
        if (!res) { // 请求失败
          this.$message.error("下载模板文件失败");
          return false;
        }
        const blob = new Blob([res.data], { // 定义一个blob
          type:
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
        });
        const downloadElement = document.createElement("a"); // 创建一个标签
        const href = window.URL.createObjectURL(blob);  // 创建a标签的链接
        downloadElement.style.display = "none";
        downloadElement.href = href;
        downloadElement.download = "设备信息";  // 下载之后文档的名字
        document.body.appendChild(downloadElement); //把a标签加入body中
        downloadElement.click();
        document.removeChild(downloadElement); // 点击之后移除a标签
        window.URL.revokeObjectURL(href); // 移除url
      });
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容