美文网首页web前端开发
JS模拟a链接下载文件流

JS模拟a链接下载文件流

作者: 爱学习的新一 | 来源:发表于2022-04-27 14:26 被阅读0次
    /**
     * 模拟a链接下载导出方法
     * @param {blob} data 数据源
     * @param {string} strFileName下载导出文件名 默认 'download'
     * @param {string} strFileType 文件类型 默认 'xlsx'
     */
    
    export function downloadFn(data, strFileName, strFileType) {
    
      var self = window,
        defaultType = "application/octet-stream",
        docType = strFileType || defaultType,
        payload = data,
        //避免带中文的文件名赋值给url
        //url = !strFileName && !strFileType && payload,
        url = payload,
        anchor = document.createElement("a"),
        toString = function(a) {
          return String(a);
        },
        myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
        fileName = strFileName || "download",
        blob,
        reader;
      myBlob = myBlob.call ? myBlob.bind(self) : Blob;
    
      if (String(this) === "true") {
        payload = [payload, docType];
        docType = payload[0];
        payload = payload[1];
      }
    
    
      if (url && url.length < 2048) {
        if (strFileName) {
          fileName = strFileName;
        } else {
          fileName = url.split("/").pop().split("?")[0];
        }
        anchor.href = url;
        //带中文url
        //   if(anchor.href.indexOf(url) !== -1){
        var ajax = new XMLHttpRequest();
        ajax.open("GET", url, true);
        ajax.responseType = 'blob';
        ajax.onload = function(e) {
          download(e.target.response, fileName, defaultType);
        };
        setTimeout(function() {
          ajax.send();
        }, 0);
        return ajax;
        // }
      }
    
    
      if (/^data\:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)) {
    
        if (payload.length > (1024 * 1024 * 1.999) && myBlob !== toString) {
          payload = dataUrlToBlob(payload);
          docType = payload.type || defaultType;
        } else {
          return navigator.msSaveBlob ?
            navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
            saver(payload);
        }
    
      }
    
      blob = payload instanceof myBlob ?
        payload :
        new myBlob([payload], {
          type: docType
        });
    
    
      function dataUrlToBlob(strUrl) {
        var parts = strUrl.split(/[:;,]/),
          type = parts[1],
          decoder = parts[2] == "base64" ? atob : decodeURIComponent,
          binData = decoder(parts.pop()),
          mx = binData.length,
          i = 0,
          uiArr = new Uint8Array(mx);
    
        for (i; i < mx; ++i) uiArr[i] = binData.charCodeAt(i);
    
        return new myBlob([uiArr], {
          type: type
        });
      }
    
      function saver(url, winMode) {
    
        if ('download' in anchor) {
          anchor.href = url;
          anchor.setAttribute("download", fileName);
          anchor.className = "download-js-link";
          anchor.innerHTML = "downloading...";
          anchor.style.display = "none";
          document.body.appendChild(anchor);
          setTimeout(function() {
            anchor.click();
            document.body.removeChild(anchor);
            if (winMode === true) {
              setTimeout(function() {
                self.URL.revokeObjectURL(anchor.href);
              }, 250);
            }
          }, 66);
          return true;
        }
    
    
        if (/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
          url = url.replace(/^data:([\w\/\-\+]+)/, defaultType);
          if (!window.open(url)) {
            if (window.confirm(
                "Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")) {
              window.location.href = url;
            }
          }
          return true;
        }
    
    
        var f = document.createElement("iframe");
        document.body.appendChild(f);
    
        if (!winMode) {
          url = "data:" + url.replace(/^data:([\w\/\-\+]+)/, defaultType);
        }
        f.src = url;
        setTimeout(function() {
          document.body.removeChild(f);
        }, 333);
    
      }
    
    
    
    
      if (navigator.msSaveBlob) {
        return navigator.msSaveBlob(blob, fileName);
      }
    
      if (self.URL) {
        saver(self.URL.createObjectURL(blob), true);
      } else {
    
        if (typeof blob === "string" || blob.constructor === toString) {
          try {
            return saver("data:" + docType + ";base64," + self.btoa(blob));
          } catch (y) {
            return saver("data:" + docType + "," + encodeURIComponent(blob));
          }
        }
    
    
        reader = new FileReader();
        reader.onload = function(e) {
          saver(this.result);
        };
        reader.readAsDataURL(blob);
      }
      return true;
    };
    

    相关文章

      网友评论

        本文标题:JS模拟a链接下载文件流

        本文链接:https://www.haomeiwen.com/subject/cuhdyrtx.html