import { Modal } from "ant-design-vue";
import { ModalConfirm } from "ant-design-vue/types/modal";
import axios, { AxiosResponse, Method } from "axios";
import NProgress from "nprogress";
import i18n from "@/locales/i18n";
import { AjaxRes } from "@/types/common";
import { messageName } from "@/config/network";
let modal: ModalConfirm;
export const ajaxDownload = (url: string, params: Record<string, unknown> = {}, method: Method = "GET", data: Record<string, unknown> = {}, name?: string) => {
return new Promise<void>((resolve, reject) => {
NProgress.start();
fileDownload(url, params, method, data)
.then((response: AxiosResponse) => {
convertRes2Blob(response, name);
resolve();
})
.catch((error) => {
NProgress.done();
if (modal) modal.destroy();
if (typeof error === "object") {
if (error.type) {
if (error.type === 404) {
Modal.error({ content: "服务端找不到文件", centered: true });
}
if (error.response) {
if (error.response.status === 404) {
Modal.error({ content: "服务端找不到文件", centered: true });
} else {
Modal.error({ content: "文件下载失败了", centered: true });
}
} else {
Modal.error({ content: "文件内容解析失败", centered: true });
}
}
reject(error);
}
});
});
};
const fileDownload = (url: string, params: Record<string, unknown>, method: Method, data: Record<string, unknown>) => {
modal = Modal.info({ title: i18n.t("文件下载"), content: i18n.t("开始下载"), centered: true, okText: i18n.t("关闭") as string });
return axios({
url,
method,
params,
data,
headers: {
Accept: "application/json",
"Content-Type": "application/json; charset=utf-8",
},
responseType: "blob",
timeout: 120000,
onDownloadProgress: (e) => {
if (e.lengthComputable) {
modal.update({ content: i18n.t("当前文件下载进度") + ":" + ((e.loaded / e.total) * 100).toFixed(2) + "%" });
if (e.loaded === e.total) {
NProgress.set(e.loaded / e.total);
modal.destroy();
}
}
},
});
};
const convertRes2Blob = async (response: AxiosResponse, name?: string) => {
let fileName = "";
const responseJson: AjaxRes = await blobToObj(response.data);
if (!responseJson.success) {
Modal.error({
title: i18n.t("接口温馨提醒"),
content: responseJson[messageName] as string,
});
modal.destroy();
NProgress.done();
return;
}
try {
fileName = response.headers["content-disposition"]?.replace(/^attachment;file(N|n)ame=/, "");
} catch (error) {
throw new Error("服务端找不到文件");
}
fileName = name ? name : fileName;
const blob = new Blob([response.data]);
if (typeof window.navigator["msSaveBlob"] !== "undefined") {
window.navigator.msSaveBlob(blob, decodeURI(fileName));
} else {
const blobURL = window.URL.createObjectURL(blob);
const tempLink = document.createElement("a");
tempLink.style.display = "none";
tempLink.href = blobURL;
tempLink.setAttribute("download", decodeURI(fileName));
if (typeof tempLink.download === "undefined") {
tempLink.setAttribute("target", "_blank");
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
window.URL.revokeObjectURL(blobURL);
}
};
export const blobToObj = (data: Blob): Promise<AjaxRes> => {
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsText(data, "utf-8");
reader.onload = function () {
try {
resolve(JSON.parse(reader.result as string));
} catch (error) {
resolve({
code: 200,
success: true,
data: null,
message: "当前信息为数据流信息,接口正常",
timestamp: "2023-10-06",
});
}
};
});
};
downloadAll() {
let allPath: any = this.pdfData.map((item) => item.filePath);
ajaxDownload("/api/base/tool/down", {}, "PUT", allPath, `${this.productCode}.zip`);
}