js vue 下载各种类型文件 更改文件名称等 可用于获取后台下载地址,并且兼容各个浏览器

 
var url='http://temporary.img.jia-r.com/exportExcelZhangFile/20/07/14/200714101940416H9F1.xls' //获取后台返回下载excel文件地址
var name='aaa' //自定下载义文件名称
this.fileLinkToStreamDownload(url, name, 'pdf')
//也可以下载其他格式文件
if (url.indexOf("https") < 0) {
              url = url.replace("http:", "https:");
  }
     if(type=='jpg'||type=='jpeg'||type=='png'){
           this.ddd(url,name,type)
 }else if(type=='pdf'){
              this.fileLinkToStreamDownload(url, name, 'pdf')
 }else{
              //location.href = url;
            this.fileLinkToStreamDownload(url, name, type)
 }
 ddd(src,name,type){
            var canvas = document.createElement('canvas');
            var img = document.createElement('img');
            img.setAttribute("crossOrigin",'Anonymous');
            img.src = src;
            let _this=this;
            img.onload = function(e) {
                canvas.width = img.width;
                canvas.height = img.height;
                var context = canvas.getContext('2d');
                context.drawImage(img, 0, 0, img.width, img.height);
                canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
                _this.downs(canvas.toDataURL(type=='jpg'?'image/jpeg':type=='jpeg'?'image/jpeg':type=='png'?'image/png':''),name,img)
            }
  },
    downs(url,name,img){
          let a= document.createElement("a")
           let imgURL=url;
          let ua = navigator.userAgent;
            if (ua.indexOf("Trident") != -1 && ua.indexOf("Windows") != -1) { // IE内核 并且  windows系统 情况下 才执行;
                    var bstr = atob(imgURL.split(',')[1])
                    var n = bstr.length
                    var u8arr = new Uint8Array(n)
                    while (n--) {
                    u8arr[n] = bstr.charCodeAt(n)
                    }
                   var blob = new Blob([u8arr])
                    window.navigator.msSaveOrOpenBlob(blob, name)
            }else if(ua.indexOf("Firefox") > -1){ //火狐兼容下载
                    let blob = this.base64ToBlob(imgURL); //new Blob([content]);
                    let evt = document.createEvent("HTMLEvents");
                    evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型,是否冒泡,是否阻止浏览器的默认行为
                    a.download = ' ';
                    a.href = URL.createObjectURL(blob);
                    a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//兼容火狐
             }else{ //谷歌兼容下载
                    img.src=imgURL;
                    // a.href = myCanvas[0].toDataURL('image/png').replace('image/png', 'image/octet-stream')
                    a.href=img.src
                    //设置下载文件的名字
                    a.download = name
                    //点击
                    a.click()
            }
          img.onload = null;//防止一直循环 
     },
     //base64转blob
    base64ToBlob(code) {
             let parts = code.split(';base64,');
             let contentType = parts[0].split(':')[1];
             let raw = window.atob(parts[1]);
             let rawLength = raw.length;
             let uInt8Array = new Uint8Array(rawLength);
            for (let i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
              }
              return new Blob([uInt8Array], {type: contentType});
       },           

 

//pdf下载
fileLinkToStreamDownload(url, fileName, type) {
          let xhr = new XMLHttpRequest();
           xhr.open('get', url, true);
           xhr.setRequestHeader('Content-Type', `application/${type}`);
           xhr.responseType = "blob";
           let _this=this;
              xhr.onload = function () {
                if (this.status == 200) {
                  //接受二进制文件流
                  var blob = this.response;
                let ua = navigator.userAgent;
                  if (ua.indexOf("Trident") != -1 && ua.indexOf("Windows") != -1) { // IE内核 并且  windows系统 情况下 才执行;
                    navigator.msSaveBlob(blob, fileName)
                  }else if(ua.indexOf("Firefox") > -1){ //火狐兼容下载
                    _this.downloadExportFile(blob, fileName, type)
                  }else{ //谷歌兼容下载
                    _this.downloadExportFile(blob, fileName, type)
                  }
                }
              }
              xhr.send();
          },
   downloadExportFile(blob, tagFileName, fileType) {
          let downloadElement = document.createElement('a');
          let href = blob;
          if (typeof blob == 'string') {
              downloadElement.target = '_blank';
          } else {
             href = window.URL.createObjectURL(blob); //创建下载的链接
           }
          downloadElement.href = href;
          downloadElement.download = tagFileName; //下载后文件名
          document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
         if (typeof blob != 'string') {
            window.URL.revokeObjectURL(href); //释放掉blob对象
         }
     },

 

posted @ 2020-07-14 10:40  西西里`  阅读(3374)  评论(0编辑  收藏  举报