38 lines
855 B
TypeScript
38 lines
855 B
TypeScript
/**
|
||
* 文件下载工具
|
||
*/
|
||
|
||
/**
|
||
* 通过 URL 下载文件
|
||
* @param url 文件下载地址
|
||
* @param filename 保存的文件名
|
||
*/
|
||
export const downloadFileFromUrl = (url: string, filename?: string) => {
|
||
try {
|
||
const link = document.createElement('a')
|
||
link.href = url
|
||
link.target = '_blank'
|
||
|
||
if (filename) {
|
||
link.download = filename
|
||
}
|
||
|
||
// 添加到DOM,触发下载,然后移除
|
||
document.body.appendChild(link)
|
||
link.click()
|
||
document.body.removeChild(link)
|
||
} catch (error) {
|
||
console.error('下载文件失败:', error)
|
||
throw error
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取文件扩展名
|
||
* @param filename 文件名或URL
|
||
*/
|
||
export const getFileExtension = (filename: string): string => {
|
||
const lastDotIndex = filename.lastIndexOf('.')
|
||
return lastDotIndex !== -1 ? filename.slice(lastDotIndex) : ''
|
||
}
|