staff_data/packages/client/src/io/download.ts

42 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-12-30 08:26:40 +08:00
/**
*
* @param url - URLundefined
* @throws {Error} URL无效或下载过程中发生错误时抛出异常
*/
export const handleDownload = (url: string | undefined): void => {
if (!url) {
throw new Error("Invalid URL provided for download");
}
const link = document.createElement("a");
try {
link.href = url;
link.download = extractFileNameFromUrl(url);
link.style.display = "none"; // 避免影响页面布局
document.body.appendChild(link);
link.click();
} finally {
// 确保无论成功与否都清理DOM元素
if (link) {
document.body.removeChild(link);
}
}
};
/**
* URL中提取文件名
* @param url - URL
* @returns
*/
const extractFileNameFromUrl = (url: string): string => {
const fileName = url.split("/").pop();
return fileName ? fileName : generateRandomFileName();
};
/**
*
* @returns
*/
const generateRandomFileName = (): string => {
const randomString = Math.random().toString(36).substring(2, 15);
return `file_${randomString}`;
};