zy-vue-library/hooks/useDownloadBlob/index.js

59 lines
2.0 KiB
JavaScript
Raw Normal View History

2025-10-22 11:19:51 +08:00
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import {getFileUrl} from "../../utils/index.js";
/**
* @param {string} url - 请求的 API 地址GET
* @param {Object} [option] - 配置项可选
* @param {string} [option.name] - 下载文件的自定义文件名不含后缀默认为当前时间戳
* @param {string} [option.type] - Blob 对象的 MIME 类型默认为 Excel 类型
* @param {Object} [option.params] - 请求时携带的查询参数对象
* @returns {Promise<any>} 如果下载成功则 resolve 响应数据失败则 reject 错误信息
*/
export default function useDownloadBlob(
url,
option = { name: "", type: "", params: {} }
) {
const FILE_URL = getFileUrl();
return new Promise((resolve, reject) => {
const finalUrl = url.indexOf(FILE_URL) === -1 ? FILE_URL + url : url;
Object.entries(option.params).forEach(([key, value]) => {
finalUrl.searchParams.append(key, value);
});
fetch(finalUrl, {
method: "GET",
mode: "cors",
headers: {
"Content-Type": "application/json",
},
})
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.blob();
})
.then((blob) => {
// 保持原有下载逻辑
const finalBlob = new Blob([blob], {
type: option.type || "application/vnd.ms-excel",
});
const downloadElement = document.createElement("a");
const href = window.URL.createObjectURL(finalBlob);
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({ data: finalBlob });
})
.catch((err) => {
ElMessage.error("导出失败");
reject(err);
});
});
}