VUE-blob方法返回文件流并下载问题

请求接口返回如下图所示:

 

先设置请求类型:

responseType: 'blob'

 


responseType: 'blob'

 exportLineStatisticsInfo(id)
        .then((resp) => {
          console.log(resp);
          let blob = new Blob([resp], { type: "application/vnd.ms-excel" });
          let objectUrl = URL.createObjectURL(blob);
          window.open(objectUrl, "_blank");
        })
        .catch((error) => {
          this.$message.error(error);
        });

返回后记得设置类型type: "application/vnd.ms-excel"

不知道类型可以直接console.log打印查看类型:

 

最后通过链接打开  直接下载

PS: 当直接使用window.open 时,遇到浏览器无法预览的文件会直接下载(如exel表格等)但遇到浏览器能预览的文件(如图片、pdf等)会打开新页面而不会下载,如果想直接下载该文件需用如下写法:

 


.then((resp) => {
     if(resp.data.size>0){
          const _res = resp.data;
          const fileName = resp.headers["content-disposition"].split("=")[1];//下载文件全名(未转码)
          let blob = new Blob([_res], {type: 'application/pdf'});
          let downloadElement = document.createElement("a");
          let href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = decodeURIComponent(fileName).split(".")[0]; //下载后文件名(转码并去掉全名后的.pdf)
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        }else{
          this.$message.error("暂无故障报告");
        }
      })
      .catch((error) => {
        this.$message.error(error);
      });  


版权声明:本文为zhufan2333原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。