feat: 资源列表批量下载优化

This commit is contained in:
2025-11-06 17:05:33 +08:00
parent 33177a56ac
commit cb66f9f7e1
15 changed files with 365 additions and 188 deletions
@@ -89,7 +89,6 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
try {
const data = await ordersApi.getOrderResources(orderNo);
console.log(`📊 Got ${data?.length || 0} resources:`, data);
setResources(Array.isArray(data) ? data : []);
setHasLoadedOnce(true);
} catch (error: any) {
@@ -129,128 +128,51 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
});
};
// 处理下载 - 通过后端代理解决跨域问题,并添加进度显示
const handleDownload = async (url: string, fileName?: string) => {
if (!url) return;
// 处理下载 - 获取URL后用 <a> 标签强制下载
const handleDownload = async (file: OrderFile, fileName?: string) => {
if (!file || !file.fileId) {
return;
}
const fileId = getFileId(url, fileName);
const finalFileName = fileName || `file_${Date.now()}`;
console.log(`⬇️ Starting download: ${url} as ${finalFileName}`);
const finalFileName = fileName || getFileName(file, 0);
const fileId = file.fileId;
// 禁用按钮,显示进度
updateDownloadProgress(fileId, 0, true);
try {
// 方式1: 通过后端代理下载(推荐 - 解决跨域问题,支持进度回调)
console.log('📌 Downloading via backend proxy...');
updateDownloadProgress(fileId, 50, true);
// 使用进度回调更新UI,流式传输时会实时更新
const blob = await ordersApi.downloadFile(url, (progress) => {
updateDownloadProgress(fileId, progress, true);
});
// 获取下载URL
const downloadUrl = await ordersApi.getFileDownloadUrl(fileId);
// blob接收完成后,设置为90%,准备触发下载
updateDownloadProgress(fileId, 90, true);
if (!downloadUrl) {
throw new Error('Failed to get download URL');
}
const blobUrl = window.URL.createObjectURL(blob as Blob);
const a = document.createElement('a');
a.href = blobUrl;
a.download = finalFileName;
a.style.display = 'none';
document.body.appendChild(a);
updateDownloadProgress(fileId, 100, false);
updateDownloadProgress(fileId, 90, true);
// 创建临时 <a> 标签并使用 download 属性强制下载
const link = document.createElement('a');
link.href = downloadUrl;
link.download = finalFileName;
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
setTimeout(() => {
a.click();
console.log(`✅ Download started via backend proxy: ${finalFileName}`);
updateDownloadProgress(fileId, 100, false);
// 延迟500ms后隐藏进度条,让用户看到完成状态
setTimeout(() => {
removeDownloadProgress(fileId);
document.body.removeChild(a);
window.URL.revokeObjectURL(blobUrl);
}, 500);
}, 0);
removeDownloadProgress(fileId);
}, 300);
return true;
} catch (error) {
console.error(`❌ Backend proxy download failed:`, error);
try {
// 方式2: 尝试 XMLHttpRequest(本地可用但跨域受限)
console.log('📌 Trying XHR method...');
updateDownloadProgress(fileId, 30, true);
return await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
// 跟踪下载进度
xhr.addEventListener('progress', (event) => {
if (event.lengthComputable) {
const percentComplete = Math.round((event.loaded / event.total) * 100);
updateDownloadProgress(fileId, percentComplete, true);
console.log(`📊 Download progress: ${percentComplete}%`);
}
});
xhr.onload = () => {
if (xhr.status === 200) {
const blob = xhr.response;
updateDownloadProgress(fileId, 90, true);
const blobUrl = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = blobUrl;
a.download = finalFileName;
a.style.display = 'none';
document.body.appendChild(a);
setTimeout(() => {
a.click();
console.log(`✅ Download started via XHR: ${finalFileName}`);
updateDownloadProgress(fileId, 100, false);
setTimeout(() => {
removeDownloadProgress(fileId);
document.body.removeChild(a);
window.URL.revokeObjectURL(blobUrl);
resolve(true);
}, 500);
}, 0);
} else {
reject(new Error(`HTTP ${xhr.status}`));
}
};
xhr.onerror = () => {
console.error('XHR download failed:', xhr.status);
reject(new Error('XHR request failed'));
};
xhr.send();
});
} catch (xhrError) {
console.error(`❌ XHR方式失败:`, xhrError);
removeDownloadProgress(fileId);
// 方式3: 降级到直接链接 + 新窗口
console.log('📌 Falling back to direct link in new window...');
if (url.includes('?')) {
window.open(`${url}&download=1`, '_blank');
} else {
window.open(`${url}?download=1`, '_blank');
}
return true;
}
removeDownloadProgress(fileId);
return false;
}
};
// 批量下载所有文件 - 调用后端批量下载接口(推荐)
// 批量下载所有文件 - 优化:直接获取每个文件的下载URL,由浏览器并发下载
// 优势:充分利用用户网络带宽,无需后端生成ZIP,下载速度更快
const handleBatchDownload = async () => {
if (!record?.orderNo) {
console.warn('⚠️ orderNo is missing');
@@ -258,89 +180,86 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
}
const orderNo = record.orderNo;
console.log(`📦 Starting batch download for order: ${orderNo}`);
console.log(`📦 Starting optimized batch download for order: ${orderNo}`);
console.log(`📊 Total files to download: ${resources.length}`);
setBatchDownloading(true);
const startTime = Date.now();
let lastUpdateTime = startTime;
let lastDownloadedBytes = 0;
try {
// 创建虚拟进度条项
updateDownloadProgress('batch_all', 0, true);
updateDownloadProgress('batch_all', 10, true);
// 调用后端批量下载接口,一次性生成ZIP
const blob = await ordersApi.batchDownloadFiles(orderNo, (downloadedBytes) => {
// 计算下载速度和已用时间
const currentTime = Date.now();
const elapsedSeconds = (currentTime - startTime) / 1000;
const speed = (downloadedBytes / (1024 * 1024)) / Math.max(elapsedSeconds, 0.1); // MB/s
let successCount = 0;
let failureCount = 0;
// 计算下载的大小(MB)
const downloadedMB = (downloadedBytes / (1024 * 1024)).toFixed(2);
console.log(`📌 Fetching download URLs for ${resources.length} files...`);
updateDownloadProgress('batch_all', 20, true);
// 存储已下载信息用于显示(使用一个特殊属性)
const progressObj = {
fileId: 'batch_all',
downloadedBytes,
downloadedMB,
speed: speed.toFixed(2),
elapsedSeconds: elapsedSeconds.toFixed(1),
progress: Math.min(90, (downloadedBytes / (1024 * 1024 * 100)) * 100),
isLoading: true
};
// 获取所有文件的下载URL
const fileDownloadMap = new Map<string, { file: OrderFile; url: string }>();
setDownloadingFiles(prev => {
const newMap = new Map(prev);
newMap.set('batch_all', progressObj as any);
return newMap;
});
console.log(`📊 已下载: ${downloadedMB}MB, 速度: ${speed.toFixed(2)}MB/s, 耗时: ${elapsedSeconds.toFixed(1)}s`);
// 分批获取URL,避免过多并发请求
for (let i = 0; i < resources.length; i++) {
const file = resources[i];
try {
const downloadUrl = await ordersApi.getFileDownloadUrl(file.fileId!);
if (downloadUrl) {
fileDownloadMap.set(file.fileId!, { file, url: downloadUrl });
successCount++;
} else {
failureCount++;
}
} catch (error) {
console.warn(`⚠️ Failed to get download URL for file ${file.fileId}:`, error);
failureCount++;
}
// 更新进度(20% - 60%)
const progress = 20 + Math.floor((i / resources.length) * 40);
updateDownloadProgress('batch_all', progress, true);
}
console.log(`✅ Got ${successCount} download URLs, ${failureCount} failed`);
if (successCount === 0) {
throw new Error('Unable to get any download URLs');
}
updateDownloadProgress('batch_all', 60, true);
// 并发下载所有文件(无并发限制)
console.log(`📌 Starting concurrent downloads for ${successCount} files...`);
const filesToDownload = Array.from(fileDownloadMap.entries());
const downloadPromises = filesToDownload.map(async ([fileId, { file, url }]) => {
try {
// 直接打开下载URL,浏览器根据响应头自动下载
window.open(url, '_blank');
console.log(`✅ Download triggered for file: ${fileId}`);
} catch (error) {
console.error(`❌ Failed to download file:`, error);
}
});
// 检查是否成功
if (!blob || blob.size === 0) {
throw new Error('下载的文件为空');
}
// 计算ZIP大小
const sizeInMB = (blob.size / (1024 * 1024)).toFixed(2);
const sizeInGB = (blob.size / (1024 * 1024 * 1024)).toFixed(2);
const totalTime = ((Date.now() - startTime) / 1000).toFixed(1);
console.log(`📊 ZIP大小: ${sizeInMB}MB (${sizeInGB}GB), 总耗时: ${totalTime}s`);
// 提示用户文件大小(流式传输,无大小限制)
if (blob.size > 500 * 1024 * 1024) {
console.warn(`⚠️ ZIP文件较大: ${sizeInGB}GB,下载可能需要一段时间`);
}
// 等待所有下载完成
await Promise.allSettled(downloadPromises);
updateDownloadProgress('batch_all', 90, true);
// 创建下载链接并触发浏览器下载
const blobUrl = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = blobUrl;
a.download = `${orderNo}.zip`;
a.style.display = 'none';
document.body.appendChild(a);
// 触发下载
a.click();
console.log(`✅ Batch download started: ${orderNo}.zip (${sizeInMB}MB)`);
const totalTime = ((Date.now() - startTime) / 1000).toFixed(1);
console.log(`✅ Batch download completed: ${successCount} files triggered, ${failureCount} failed, cost ${totalTime}s`);
updateDownloadProgress('batch_all', 100, false);
// 清理资源
// 清理进度条
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(blobUrl);
removeDownloadProgress('batch_all');
}, 500);
// 提示用户
const sizeDisplay = blob.size > 1024 * 1024 * 1024 ? `${sizeInGB}GB` : `${sizeInMB}MB`;
const message = `✅ 批量下载成功启动!\n\n📦 文件: ${orderNo}.zip\n💾 大小: ${sizeDisplay}\n⏱️ 耗时: ${totalTime}s\n\n📋 请检查浏览器下载列表`;
const message = `✅ 批量下载已启动!\n\n📦 文件数: ${successCount}/${resources.length}\n⏱️ 耗时: ${totalTime}s\n\n📋 所有文件并发下载中,请检查浏览器下载列表\n💡 如果文件过多,建议后台运行浏览器以加快下载`;
console.log(`🎉 ${message}`);
alert(message);
@@ -452,8 +371,8 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
title={isDownloading ? `下载中... ${downloadState?.progress || 0}%` : '下载'}
onClick={async (e) => {
e.stopPropagation();
if (item.viewUrl && !isDownloading) {
await handleDownload(item.viewUrl, fileName);
if (item && !isDownloading) {
await handleDownload(item, fileName);
}
}}
style={{
@@ -517,8 +436,8 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
disabled={isDownloading}
title={isDownloading ? `下载中... ${downloadState?.progress || 0}%` : '下载'}
onClick={async () => {
if (item.viewUrl && !isDownloading) {
await handleDownload(item.viewUrl, fileName);
if (item && !isDownloading) {
await handleDownload(item, fileName);
}
}}
style={{ marginLeft: '8px' }}
@@ -321,6 +321,12 @@ export const ordersApi = {
}
},
// 获取单个文件的下载URL
getFileDownloadUrl: async (fileId: string) => {
const res = await request(`/api-order/files/file/download/${fileId}`, { method: 'GET' });
return (res as any) || '';
},
// 下载文件 - 通过后端代理(解决跨域问题)
// 优化:改为流式传输,支持大文件下载、断点续传
// 注意:使用 XMLHttpRequest 以支持进度回调和流式传输