js前端流的方式下载execl


infoDownload(params){
        let url = `${BaseUrls.infoDownload}?${translateParam(params)}`
        downloadExecl(url)
    },


//
导出execl文件 export function downloadExecl(url,filename='') { axios({ method: "GET", url: url, responseType: "blob", // data: {}, //此处配置token和入参类型 // transformRequest: [function(fData, headers) { // headers['Content-Type'] = 'application/json' // headers['Authorization'] = 'RDS eyJhbGciOiJIUzUxMiJ9.eyJyYW5kb21LZXkiOiIwLjI4MjIwNTI2OTQ2MjgyMTEiLCJzdWIiOiJjZWQ0NTViOTAyNDRhMmZlZDBjMmIzNmI4MjY1ZWY4MiIsImV4cCI6MTYwMTI5ODg2OCwiaWF0IjoxNjAxMjU1NjY4fQ.kGmaiXn8qZfC1ZnHCwWO6rMcmO_a1u60CsL-9oANV81Nv-nD7S2crDGpAGTECXxYcVvM6R3Uyj13UuZnBrSfVQ.wmrds142' // return JSON.stringify(fData) // }] }).then((res) => { if(null != res.headers['content-disposition']){ filename = res.headers['content-disposition'].split('=')[1]; }else { filename = new Date().getTime() + '.xls'

    }
    fileDownload(res.data, filename);
  }).catch((error) => {
    alert("网络请求出错!", error)
  })
}

function fileDownload(data, fileName) {
  let blob = new Blob([data], {
    type: "application/octet-stream"
  });
  let filename = fileName || "filename.xls";
  if (typeof window.navigator.msSaveBlob !== "undefined") {
    window.navigator.msSaveBlob(blob, filename);
  } else {
    var blobURL = window.URL.createObjectURL(blob);
    var tempLink = document.createElement("a");
    tempLink.style.display = "none";
    tempLink.href = blobURL;
    tempLink.setAttribute("download", filename);
    if (typeof tempLink.download === "undefined") {
      tempLink.setAttribute("target", "_blank");
    }
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
    window.URL.revokeObjectURL(blobURL);
  }
}
  
原文地址:https://www.cnblogs.com/sinceForever/p/13743788.html