download.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * 通过api下载文件
  3. * @param {AxiosPromise} fetchFunc 下载接口
  4. * @param {String}} fileName 文件名
  5. * @returns boolean
  6. */
  7. export function downloadByApi(fetchFunc, fileName) {
  8. return fetchFunc()
  9. .then(res => {
  10. const filename =
  11. fileName || parseDownloadFilename(res.headers["content-disposition"]);
  12. downloadByBlob(new Blob([res.data]), filename);
  13. return true;
  14. })
  15. .catch(() => {
  16. return Promise.reject();
  17. });
  18. }
  19. /**
  20. * 下载blob
  21. * @param {Blob} data blob对象
  22. * @param {String} filename 文件名
  23. */
  24. export function downloadByBlob(data, filename) {
  25. const blobUrl = URL.createObjectURL(data);
  26. const tempLink = document.createElement("a");
  27. tempLink.style.display = "none";
  28. tempLink.href = blobUrl;
  29. tempLink.setAttribute("download", filename);
  30. if (tempLink.download === "undefined") {
  31. tempLink.setAttribute("target", "_blank");
  32. }
  33. document.body.appendChild(tempLink);
  34. tempLink.click();
  35. document.body.removeChild(tempLink);
  36. window.URL.revokeObjectURL(blobUrl);
  37. }
  38. const parseDownloadFilename = dispositionInfo => {
  39. if (!dispositionInfo) return;
  40. const strs = dispositionInfo.split(";");
  41. let filename = "";
  42. strs
  43. .map(item => item.split("="))
  44. .find(item => {
  45. if (item[0].indexOf("filename") !== -1) {
  46. filename = decodeURI(item[1]);
  47. }
  48. });
  49. return filename;
  50. };