download.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { AxiosResponse } from "axios";
  2. const parseDownloadFilename = (dispositionInfo: string): string => {
  3. if (!dispositionInfo) return "";
  4. const matchs = dispositionInfo.match(/attachment;filename=(.*)/) || [];
  5. const filename = matchs[1];
  6. return filename ? decodeURI(filename) : "";
  7. };
  8. interface ApiFunc {
  9. (): Promise<AxiosResponse<Blob, any>>;
  10. }
  11. /**
  12. * 通过api下载文件
  13. * @param axiosFetchFunc axios请求方法
  14. * @param fileName 文件保存名称
  15. * @returns
  16. */
  17. export function downloadBlobByApi(axiosFetchFunc: ApiFunc, fileName?: string) {
  18. return axiosFetchFunc().then((res: AxiosResponse) => {
  19. // console.log(res);
  20. const filename =
  21. fileName || parseDownloadFilename(res.headers["content-disposition"]);
  22. downloadByBlob(new Blob([res.data]), filename);
  23. return true;
  24. });
  25. }
  26. /**
  27. * 下载blob
  28. * @param {Blob} data blob对象
  29. * @param {String} filename 文件名
  30. */
  31. export function downloadByBlob(data: Blob, filename?: string) {
  32. const blobUrl = window.URL.createObjectURL(data);
  33. downloadByUrl(blobUrl, filename);
  34. }
  35. /**
  36. * 下载url
  37. * @param {String} url 文件下载地址
  38. * @param {String}} filename 文件名
  39. */
  40. export function downloadByUrl(url: string, filename?: string) {
  41. const tempLink = document.createElement("a");
  42. tempLink.style.display = "none";
  43. tempLink.href = url;
  44. let fileName = filename;
  45. if (!fileName) {
  46. const strs = url.split("/").pop() || "";
  47. fileName = strs.split("?")[0];
  48. }
  49. tempLink.setAttribute("download", fileName);
  50. if (tempLink.download === "undefined") {
  51. tempLink.setAttribute("target", "_blank");
  52. }
  53. document.body.appendChild(tempLink);
  54. tempLink.click();
  55. document.body.removeChild(tempLink);
  56. window.URL.revokeObjectURL(url);
  57. }
  58. /**
  59. * 通过url获得dataURL
  60. * @param url 链接
  61. * @returns dataURL
  62. */
  63. export function toBlobByUrl(url: string) {
  64. return fetch(url).then((response) => {
  65. return response.blob();
  66. });
  67. }