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

This commit is contained in:
2025-11-04 17:32:28 +08:00
parent 46c0976fdf
commit 33177a56ac
4 changed files with 517 additions and 136 deletions
@@ -24,6 +24,12 @@ interface OrderResourcesModalProps {
onCancel: () => void;
}
interface DownloadProgress {
fileId: string | number;
progress: number; // 0-100
isLoading: boolean;
}
// 判断文件类型(通过 MIME type 或文件扩展名)
const isImageFile = (file: OrderFile): boolean => {
const fileType = file.fileType?.toLowerCase() || '';
@@ -61,6 +67,7 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
const [error, setError] = useState<string | null>(null);
const [batchDownloading, setBatchDownloading] = useState(false);
const [downloadingFiles, setDownloadingFiles] = useState<Map<string | number, DownloadProgress>>(new Map());
// 当弹窗打开时加载资源列表
const loadResources = useCallback(async () => {
@@ -99,17 +106,51 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
const images = resources.filter(isImageFile);
const videos = resources.filter(isVideoFile);
// 处理下载 - 通过后端代理解决跨域问题
// 生成唯一的文件ID
const getFileId = (url: string | undefined, fileName?: string): string => {
return fileName || url as string;
};
// 更新下载进度
const updateDownloadProgress = (fileId: string | number, progress: number, isLoading: boolean = true) => {
setDownloadingFiles(prev => {
const newMap = new Map(prev);
newMap.set(fileId, { fileId, progress, isLoading });
return newMap;
});
};
// 移除下载进度
const removeDownloadProgress = (fileId: string | number) => {
setDownloadingFiles(prev => {
const newMap = new Map(prev);
newMap.delete(fileId);
return newMap;
});
};
// 处理下载 - 通过后端代理解决跨域问题,并添加进度显示
const handleDownload = async (url: string, fileName?: string) => {
if (!url) return;
const fileId = getFileId(url, fileName);
const finalFileName = fileName || `file_${Date.now()}`;
console.log(`⬇️ Starting download: ${url} as ${finalFileName}`);
// 禁用按钮,显示进度
updateDownloadProgress(fileId, 0, true);
try {
// 方式1: 通过后端代理下载(推荐 - 解决跨域问题)
// 方式1: 通过后端代理下载(推荐 - 解决跨域问题,支持进度回调)
console.log('📌 Downloading via backend proxy...');
const blob = await ordersApi.downloadFile(url);
// 使用进度回调更新UI,流式传输时会实时更新
const blob = await ordersApi.downloadFile(url, (progress) => {
updateDownloadProgress(fileId, progress, true);
});
// blob接收完成后,设置为90%,准备触发下载
updateDownloadProgress(fileId, 90, true);
const blobUrl = window.URL.createObjectURL(blob as Blob);
const a = document.createElement('a');
@@ -118,14 +159,19 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
a.style.display = 'none';
document.body.appendChild(a);
updateDownloadProgress(fileId, 90, true);
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);
}, 100);
}, 500);
}, 0);
return true;
@@ -135,14 +181,27 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
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;
@@ -153,12 +212,14 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
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);
}, 100);
}, 500);
}, 0);
} else {
reject(new Error(`HTTP ${xhr.status}`));
@@ -174,6 +235,7 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
});
} catch (xhrError) {
console.error(`❌ XHR方式失败:`, xhrError);
removeDownloadProgress(fileId);
// 方式3: 降级到直接链接 + 新窗口
console.log('📌 Falling back to direct link in new window...');
@@ -188,7 +250,7 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
}
};
// 批量下载所有文件 - 并发调用单个文件下载接口
// 批量下载所有文件 - 调用后端批量下载接口(推荐)
const handleBatchDownload = async () => {
if (!record?.orderNo) {
console.warn('⚠️ orderNo is missing');
@@ -196,65 +258,104 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
}
const orderNo = record.orderNo;
console.log(`⬇️ Starting batch download for order: ${orderNo}`);
console.log(`📦 Starting 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 {
// 并发下载所有文件 - 让浏览器自动管理并发
const downloadPromises = resources.map(async (file, index) => {
if (!file.viewUrl) {
console.warn(`⚠️ Skipping file without URL: ${file.filePath}`);
return false;
}
// 创建虚拟进度条项
updateDownloadProgress('batch_all', 0, true);
const fileName = file.filePath ? file.filePath.split('/').pop() : `file_${index + 1}`;
console.log(`📥 Queuing download (${index + 1}/${resources.length}): ${fileName}`);
// 调用后端批量下载接口,一次性生成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
try {
// 调用单个文件下载接口获取 blob
const blob = await ordersApi.downloadFile(file.viewUrl);
// 计算下载的大小(MB)
const downloadedMB = (downloadedBytes / (1024 * 1024)).toFixed(2);
// 创建下载链接并触发浏览器下载
const blobUrl = window.URL.createObjectURL(blob as Blob);
const a = document.createElement('a');
a.href = blobUrl;
if (fileName != null) {
a.download = fileName;
}else {
a.download = '文件下载';
}
a.style.display = 'none';
document.body.appendChild(a);
// 添加延迟以错开下载请求,避免浏览器并发限制
await new Promise((resolve) => setTimeout(resolve, index * 150));
a.click();
console.log(`✅ Download triggered: ${fileName}`);
// 存储已下载信息用于显示(使用一个特殊属性)
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
};
// 清理资源
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(blobUrl);
}, 500);
return true;
} catch (error) {
console.error(`❌ Failed to download: ${fileName}`, error);
return false;
}
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`);
});
// 等待所有下载请求完成(不等待浏览器下载完成)
const results = await Promise.all(downloadPromises);
const successCount = results.filter((r) => r).length;
const failureCount = results.filter((r) => !r).length;
// 检查是否成功
if (!blob || blob.size === 0) {
throw new Error('下载的文件为空');
}
const message = `✅ 批量下载已启动!\n\n成功启动: ${successCount}/${resources.length}\n失败: ${failureCount}\n\n📥 文件已经全部下载完成\n📋 请检查浏览器下载列表`;
// 计算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,下载可能需要一段时间`);
}
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)`);
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📋 请检查浏览器下载列表`;
console.log(`🎉 ${message}`);
alert(message);
} catch (error) {
console.error(`❌ Batch download failed:`, error);
alert('批量下载失败,请重试');
// 检查具体错误信息
const errorMsg = error instanceof Error ? error.message : String(error);
if (errorMsg.includes('无效') || errorMsg.includes('为空')) {
alert(`⚠️ 文件获取失败!\n\n${errorMsg}\n\n💡 请检查订单资源是否存在`);
} else {
alert('批量下载失败,请重试');
}
removeDownloadProgress('batch_all');
} finally {
setBatchDownloading(false);
}
@@ -276,6 +377,10 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
) : (
images.map((item, idx) => {
const fileName = getFileName(item, idx);
const fileId = getFileId(item.viewUrl, fileName);
const downloadState = downloadingFiles.get(fileId);
const isDownloading = !!downloadState && downloadState.isLoading;
return (
<Tooltip key={item.id || idx} title={fileName}>
<div
@@ -313,13 +418,41 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
}}>
{fileName}
</div>
{/* 下载进度条 */}
{downloadState && (
<div
style={{
position: 'absolute',
bottom: '0',
left: '0',
right: '0',
height: '3px',
backgroundColor: 'rgba(0,0,0,0.1)',
overflow: 'hidden'
}}
>
<div
style={{
height: '100%',
backgroundColor: '#1890ff',
width: `${downloadState.progress}%`,
transition: 'width 0.3s ease'
}}
/>
</div>
)}
<Button
type="primary"
size="small"
icon={<DownloadOutlined />}
loading={isDownloading}
disabled={isDownloading}
title={isDownloading ? `下载中... ${downloadState?.progress || 0}%` : '下载'}
onClick={async (e) => {
e.stopPropagation();
if (item.viewUrl) {
if (item.viewUrl && !isDownloading) {
await handleDownload(item.viewUrl, fileName);
}
}}
@@ -327,7 +460,7 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
position: 'absolute',
top: '4px',
right: '4px',
opacity: 0.8
opacity: isDownloading ? 0.6 : 0.8
}}
/>
</div>
@@ -347,6 +480,10 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
<div style={{ display: 'grid', gap: '16px' }}>
{videos.map((item, idx) => {
const fileName = getFileName(item, idx);
const fileId = getFileId(item.viewUrl, fileName);
const downloadState = downloadingFiles.get(fileId);
const isDownloading = !!downloadState && downloadState.isLoading;
return (
<div
key={item.id || idx}
@@ -364,8 +501,9 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
position: 'relative'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1 }}>
<PlayCircleOutlined style={{ fontSize: '18px', color: '#1890ff' }} />
<span style={{ fontWeight: 500, maxWidth: '400px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{fileName}
@@ -375,16 +513,42 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
type="primary"
size="small"
icon={<DownloadOutlined />}
loading={isDownloading}
disabled={isDownloading}
title={isDownloading ? `下载中... ${downloadState?.progress || 0}%` : '下载'}
onClick={async () => {
if (item.viewUrl) {
if (item.viewUrl && !isDownloading) {
await handleDownload(item.viewUrl, fileName);
}
}}
style={{ marginLeft: '8px' }}
>
下载
{isDownloading ? `下载中 ${downloadState?.progress || 0}%` : '下载'}
</Button>
</div>
{/* 下载进度条 */}
{downloadState && (
<div
style={{
marginBottom: '12px',
height: '4px',
backgroundColor: 'rgba(0,0,0,0.1)',
borderRadius: '2px',
overflow: 'hidden'
}}
>
<div
style={{
height: '100%',
backgroundColor: '#1890ff',
width: `${downloadState.progress}%`,
transition: 'width 0.3s ease'
}}
/>
</div>
)}
{/* 视频播放器 */}
<div style={{
marginBottom: '12px',
@@ -432,6 +596,17 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
</div>
);
// 计算批量下载进度
const batchDownloadProgress = React.useMemo(() => {
const batchDownloads = Array.from(downloadingFiles.values()).filter(d =>
typeof d.fileId === 'string' && d.fileId.startsWith('batch_')
);
if (batchDownloads.length === 0) return 0;
const totalProgress = batchDownloads.reduce((sum, d) => sum + d.progress, 0);
return Math.round(totalProgress / batchDownloads.length);
}, [downloadingFiles]);
// 使用 effect 在 visible 变化时加载资源
React.useEffect(() => {
if (visible) {
@@ -458,10 +633,19 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
type="primary"
icon={<DownloadOutlined />}
loading={batchDownloading}
disabled={resources.length === 0 || loading}
disabled={resources.length === 0 || loading || batchDownloading}
onClick={handleBatchDownload}
title={batchDownloading ? `批量下载中...` : '下载全部文件'}
>
下载全部文件
{batchDownloading ? (() => {
const batchProgress = Array.from(downloadingFiles.values()).find(
d => typeof d.fileId === 'string' && d.fileId === 'batch_all'
);
if (batchProgress && (batchProgress as any).downloadedMB) {
return `下载中... ${(batchProgress as any).downloadedMB}MB (${(batchProgress as any).speed}MB/s)`;
}
return `下载中... ${batchDownloadProgress}%`;
})() : '下载全部文件'}
</Button>,
]}
>