12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- import { AxiosResponse } from "axios";
- const parseDownloadFilename = (dispositionInfo: string): string => {
- if (!dispositionInfo) return "";
- const matchs = dispositionInfo.match(/attachment;filename=(.*)/) || [];
- const filename = matchs[1];
- return filename ? decodeURI(filename) : "";
- };
- interface ApiFunc {
- (): Promise<AxiosResponse<Blob, any>>;
- }
- /**
- * 通过api下载文件
- * @param axiosFetchFunc axios请求方法
- * @param fileName 文件保存名称
- * @returns
- */
- export function downloadBlobByApi(axiosFetchFunc: ApiFunc, fileName?: string) {
- return axiosFetchFunc().then((res: AxiosResponse) => {
- // console.log(res);
- const filename =
- fileName || parseDownloadFilename(res.headers["content-disposition"]);
- downloadByBlob(new Blob([res.data]), filename);
- return true;
- });
- }
- /**
- * 下载blob
- * @param {Blob} data blob对象
- * @param {String} filename 文件名
- */
- export function downloadByBlob(data: Blob, filename?: string) {
- const blobUrl = window.URL.createObjectURL(data);
- downloadByUrl(blobUrl, filename);
- }
- /**
- * 下载url
- * @param {String} url 文件下载地址
- * @param {String}} filename 文件名
- */
- export function downloadByUrl(url: string, filename?: string) {
- const tempLink = document.createElement("a");
- tempLink.style.display = "none";
- tempLink.href = url;
- let fileName = filename;
- if (!fileName) {
- const strs = url.split("/").pop() || "";
- fileName = strs.split("?")[0];
- }
- 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(url);
- }
- /**
- * 通过url获得dataURL
- * @param url 链接
- * @returns dataURL
- */
- export function toBlobByUrl(url: string) {
- return fetch(url).then((response) => {
- return response.blob();
- });
- }
|