37 lines
1.2 KiB
JavaScript
37 lines
1.2 KiB
JavaScript
|
|
import { ElMessage } from "element-plus";
|
||
|
|
import dayjs from "dayjs";
|
||
|
|
import axios from "axios";
|
||
|
|
|
||
|
|
export default function useDownloadBlob(
|
||
|
|
url,
|
||
|
|
option = { name: "", type: "", params: {} }
|
||
|
|
) {
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
axios
|
||
|
|
.get(url, { responseType: "blob", params: { ...option.params } })
|
||
|
|
.then((resData) => {
|
||
|
|
if (resData.data.type === "application/json") {
|
||
|
|
throw new Error("导出失败");
|
||
|
|
}
|
||
|
|
const blob = new Blob([resData.data], {
|
||
|
|
type: option.type || "application/vnd.ms-excel",
|
||
|
|
});
|
||
|
|
const downloadElement = document.createElement("a");
|
||
|
|
const href = window.URL.createObjectURL(blob);
|
||
|
|
downloadElement.style.display = "none";
|
||
|
|
downloadElement.href = href;
|
||
|
|
downloadElement.download =
|
||
|
|
option.name || dayjs().format("YYYY-MM-DD HH:mm:ss");
|
||
|
|
document.body.appendChild(downloadElement);
|
||
|
|
downloadElement.click();
|
||
|
|
document.body.removeChild(downloadElement);
|
||
|
|
window.URL.revokeObjectURL(href);
|
||
|
|
resolve(resData);
|
||
|
|
})
|
||
|
|
.catch((err) => {
|
||
|
|
ElMessage.error("导出失败");
|
||
|
|
reject(err);
|
||
|
|
});
|
||
|
|
});
|
||
|
|
}
|