59 lines
		
	
	
		
			2.0 KiB
		
	
	
	
		
			JavaScript
		
	
	
			
		
		
	
	
			59 lines
		
	
	
		
			2.0 KiB
		
	
	
	
		
			JavaScript
		
	
	
| 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);
 | ||
|       });
 | ||
|   });
 | ||
| }
 |