// 图片/文件下载 /** * @download 下载方法 * @param url 下载地址 * @param name 文件名称 */ const Fileonload = (url: any, name: any) => { // 创建一个 XMLHttpRequest 对象 const xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.responseType = "blob"; // 设置响应类型为 blob xhr.onload = function () { if (xhr.status === 200) { const blob = xhr.response; // 获取响应的 blob 对象 const a = document.createElement("a"); // 生成一个 a 元素 const event = new MouseEvent("click"); // 创建一个单击事件 // 创建一个 URL 对象 const downloadUrl = URL.createObjectURL(blob); a.href = downloadUrl; // 将生成的 URL 设置为 a.href 属性 a.download = name; // 设置文件名称 // 触发 a 的单击事件 a.dispatchEvent(event); // 释放 URL 对象 URL.revokeObjectURL(downloadUrl); } else { console.error("下载失败,状态码:", xhr.status); } }; xhr.onerror = function () { console.error("请求失败"); }; xhr.send(); // 发送请求 }; /** * * @param formatFileSize 文件大小单位转换 * @param size 文件size */ function formatFileSize(size: any) { let Size = Number(size); if (Size < 0) { return "大小无效"; } const units = ["B", "KB", "MB"]; let index = 0; let formattedSize = Size; while (formattedSize >= 1024 && index < units.length - 1) { formattedSize /= 1024; index++; } return `${formattedSize.toFixed(0)} ${units[index]}`; } /** * @processFileName 处理文件名 * @param fileName 文件名称 * @returns */ // 提取文件名中下划线前面的部分 const processFileName = (fileName: any) => { const index = fileName?.lastIndexOf('_'); // 查找最后一个下划线的位置 if (index !== -1) { return fileName.substring(0, index) + fileName.substring(fileName.lastIndexOf('.')); // 返回下划线前面的部分和文件后缀 } else { return fileName; // 如果没有找到下划线,直接返回原文件名 } }; export { Fileonload, formatFileSize, processFileName }