下载文件或查看后台返回的图片或pdf

需求

下载文件
在线预览后台返回的图片
在线预览后台返回的pdf

思路

虽然是三种需求,但实现思路基本一致,主要有两点:

  1. 接收数据为blob文件流格式,将ajax请求的响应类型responseType设置为blob;
  2. 将文件流建立一个网页缓存,主要通过URL.createObjectURL()方法实现;

之后将下载按钮的href、图片的src属性指向这个缓存链接就可以

pdf比较特殊,要通过window.open打开这个链接就可以,但ie浏览器本身不支持打开pdf文件,只能下载

代码

this.$axios({
     url: "url",
     method: "post",
     data: {},
     responseType: 'blob'
}).then((result) => {
    /*下载处理*/
    var fileName = decodeURI(result.headers["content-disposition"]).split("=")[1];
    //ie兼容
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
         window.navigator.msSaveOrOpenBlob(new Blob([result.data]), fileName);
    } else {
         let url = window.URL.createObjectURL(new Blob([result.data]));
         let link = document.createElement('a');
         link.style.display = 'none';
         link.href = url;
         link.setAttribute('download', fileName);
         document.body.appendChild(link);
         link.click();
    }
    
    
    /*图片处理*/
    let type = result.headers["content-disposition"].split(".")[1];
    if (type == "bmp" || type == "jpg" || type == "png" || type == "jpeg") {
         let url = window.URL.createObjectURL(new Blob([result.data]));
         img.src = url; //具体img标签根据自己情况获取
    }
    
    
    /*pdf处理*/
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          var fileName = decodeURI(result.headers["content-disposition"]).split("=")[1];
          window.navigator.msSaveOrOpenBlob(new Blob([result.data]), fileName);
    } else {
          let blob = new window.Blob([result.data], {
                type: 'application/pdf;charset-UTF-8',
          });
          const href = URL.createObjectURL(blob);
          window.open(href);
    }
})

个人对这块理解不是很深,如果有什么不对的地方,欢迎指正

posted @ 2022-04-28 13:40  前端泥石流  阅读(489)  评论(0)    收藏  举报