refactor: 优化文件下载功能和移除预览点击

This commit is contained in:
wangqiao
2025-08-30 11:52:36 +08:00
parent 966c5feb5e
commit 3153a35daf
2 changed files with 44 additions and 9 deletions

View File

@ -88,15 +88,49 @@ export const formatNumber = (value?: number, decimals = 0) => {
* @param url 文件地址
* @param filename 文件名
*/
export const downloadFile = (url: string, filename: string) => {
const a = document.createElement('a')
a.href = url
a.download = filename || 'download' // 设置下载的文件名
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
export const downloadFile = async (url: string, filename: string) => {
if (!process.client) return;
try {
const response = await fetch(url);
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0;
const stream = new ReadableStream({
async start(controller) {
while (true) {
const { done, value } = await reader.read();
if (done) {
controller.close();
return;
}
receivedLength += value.length;
const progress = (receivedLength / contentLength * 100).toFixed(2);
console.log(`下载进度: ${progress}%`);
controller.enqueue(value);
}
}
});
const blob = await new Response(stream).blob();
const objectURL = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = objectURL;
a.download = filename || 'download';
a.style.display = 'none';
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(objectURL);
document.body.removeChild(a);
} catch (error) {
console.error('下载失败:', error);
// 可添加错误提示逻辑
}
}
/**
* 判断传入的参数是否为数组