/** * 通过api下载文件 * @param {AxiosPromise} fetchFunc 下载接口 * @param {String}} fileName 文件名 * @returns boolean */ export function downloadByApi(fetchFunc, fileName) { return fetchFunc() .then(res => { const filename = fileName || parseDownloadFilename(res.headers["content-disposition"]); downloadByBlob(new Blob([res.data]), filename); return true; }) .catch(() => { return Promise.reject(); }); } /** * 下载blob * @param {Blob} data blob对象 * @param {String} filename 文件名 */ export function downloadByBlob(data, filename) { const blobUrl = URL.createObjectURL(data); const tempLink = document.createElement("a"); tempLink.style.display = "none"; tempLink.href = blobUrl; tempLink.setAttribute("download", filename); if (tempLink.download === "undefined") { tempLink.setAttribute("target", "_blank"); } document.body.appendChild(tempLink); tempLink.click(); document.body.removeChild(tempLink); window.URL.revokeObjectURL(blobUrl); } const parseDownloadFilename = dispositionInfo => { if (!dispositionInfo) return; const strs = dispositionInfo.split(";"); let filename = ""; strs .map(item => item.split("=")) .find(item => { if (item[0].indexOf("filename") !== -1) { filename = decodeURI(item[1]); } }); return filename; };