feat: 1:资源列表批量下载优化,可以下载为zip
2:添加删除某个图片或者视频功能
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
import React, { useState, useCallback } from 'react';
|
||||
import { Modal, Spin, Empty, Image, Badge, Tabs, Space, Button, Tooltip } from 'antd';
|
||||
import { DownloadOutlined, PictureOutlined, PlayCircleOutlined } from '@ant-design/icons';
|
||||
import { Modal, Spin, Empty, Image, Badge, Tabs, Space, Button, Tooltip, message, Popconfirm } from 'antd';
|
||||
import { DownloadOutlined, PictureOutlined, PlayCircleOutlined, FileZipOutlined, DeleteOutlined } from '@ant-design/icons';
|
||||
import { ordersApi } from '@/services/orders';
|
||||
import type { OrderItem } from '@/services/orders';
|
||||
import {dateFormatterMap} from "@ant-design/pro-components";
|
||||
import JSZip from 'jszip';
|
||||
import { saveAs } from 'file-saver';
|
||||
|
||||
interface OrderFile {
|
||||
id?: number | string;
|
||||
@@ -128,6 +130,27 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
||||
});
|
||||
};
|
||||
|
||||
// 处理删除文件
|
||||
const handleDeleteFile = async (fileId: number | string) => {
|
||||
try {
|
||||
message.loading('正在删除文件...', 0);
|
||||
|
||||
// 调用删除接口
|
||||
await ordersApi.deleteOrderFile(Number(fileId));
|
||||
|
||||
message.destroy();
|
||||
message.success('删除成功');
|
||||
|
||||
// 重新加载资源列表
|
||||
setHasLoadedOnce(false);
|
||||
await loadResources();
|
||||
} catch (error) {
|
||||
message.destroy();
|
||||
console.error('删除文件失败:', error);
|
||||
message.error('删除失败,请重试');
|
||||
}
|
||||
};
|
||||
|
||||
// 处理下载 - 获取URL后用 <a> 标签强制下载
|
||||
const handleDownload = async (file: OrderFile, fileName?: string) => {
|
||||
if (!file || !file.fileId) {
|
||||
@@ -171,109 +194,113 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
||||
}
|
||||
};
|
||||
|
||||
// 批量下载所有文件 - 优化:直接获取每个文件的下载URL,由浏览器并发下载
|
||||
// 优势:充分利用用户网络带宽,无需后端生成ZIP,下载速度更快
|
||||
// 批量下载所有文件为 ZIP - 前端打包
|
||||
const handleBatchDownload = async () => {
|
||||
if (!record?.orderNo) {
|
||||
console.warn('⚠️ orderNo is missing');
|
||||
message.warning('订单号缺失');
|
||||
return;
|
||||
}
|
||||
|
||||
const orderNo = record.orderNo;
|
||||
console.log(`📦 Starting optimized batch download for order: ${orderNo}`);
|
||||
console.log(`📊 Total files to download: ${resources.length}`);
|
||||
console.log(`📦 开始批量下载并打包为 ZIP: ${orderNo}`);
|
||||
console.log(`📊 总文件数: ${resources.length}`);
|
||||
setBatchDownloading(true);
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
try {
|
||||
// 创建虚拟进度条项
|
||||
// 创建 JSZip 实例
|
||||
const zip = new JSZip();
|
||||
|
||||
// 更新进度
|
||||
updateDownloadProgress('batch_all', 0, true);
|
||||
updateDownloadProgress('batch_all', 10, true);
|
||||
|
||||
let successCount = 0;
|
||||
let failureCount = 0;
|
||||
|
||||
console.log(`📌 Fetching download URLs for ${resources.length} files...`);
|
||||
// 并发下载所有文件并添加到 ZIP
|
||||
console.log(`📌 开始下载 ${resources.length} 个文件...`);
|
||||
updateDownloadProgress('batch_all', 20, true);
|
||||
|
||||
// 获取所有文件的下载URL
|
||||
const fileDownloadMap = new Map<string, { file: OrderFile; url: string }>();
|
||||
|
||||
// 分批获取URL,避免过多并发请求
|
||||
for (let i = 0; i < resources.length; i++) {
|
||||
const file = resources[i];
|
||||
const downloadPromises = resources.map(async (file, index) => {
|
||||
try {
|
||||
const downloadUrl = await ordersApi.getFileDownloadUrl(file.fileId!);
|
||||
if (downloadUrl) {
|
||||
fileDownloadMap.set(file.fileId!, { file, url: downloadUrl });
|
||||
successCount++;
|
||||
} else {
|
||||
if (!file.fileId) {
|
||||
failureCount++;
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取下载 URL
|
||||
const downloadUrl = await ordersApi.getFileDownloadUrl(file.fileId);
|
||||
if (!downloadUrl) {
|
||||
failureCount++;
|
||||
return;
|
||||
}
|
||||
|
||||
// 下载文件内容
|
||||
console.log(`⏬ 正在下载文件 ${index + 1}/${resources.length}: ${file.fileId}`);
|
||||
const response = await fetch(downloadUrl);
|
||||
if (!response.ok) {
|
||||
console.error(`❌ 下载失败: ${file.fileId}`);
|
||||
failureCount++;
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取文件内容为 blob
|
||||
const blob = await response.blob();
|
||||
const fileName = getFileName(file, index);
|
||||
|
||||
// 添加到 ZIP
|
||||
zip.file(fileName, blob);
|
||||
successCount++;
|
||||
console.log(`✅ 已添加到 ZIP: ${fileName}`);
|
||||
|
||||
// 更新进度(20% - 70%)
|
||||
const progress = 20 + Math.round(((index + 1) / resources.length) * 50);
|
||||
updateDownloadProgress('batch_all', progress, true);
|
||||
} catch (error) {
|
||||
console.warn(`⚠️ Failed to get download URL for file ${file.fileId}:`, error);
|
||||
console.error(`❌ 处理文件失败:`, 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);
|
||||
}
|
||||
});
|
||||
|
||||
// 等待所有下载完成
|
||||
await Promise.allSettled(downloadPromises);
|
||||
updateDownloadProgress('batch_all', 90, true);
|
||||
|
||||
const totalTime = ((Date.now() - startTime) / 1000).toFixed(1);
|
||||
console.log(`✅ Batch download completed: ${successCount} files triggered, ${failureCount} failed, cost ${totalTime}s`);
|
||||
if (successCount === 0) {
|
||||
throw new Error('没有文件成功下载');
|
||||
}
|
||||
|
||||
// 生成 ZIP 文件
|
||||
console.log(`📦 正在生成 ZIP 文件,包含 ${successCount} 个文件...`);
|
||||
updateDownloadProgress('batch_all', 80, true);
|
||||
|
||||
const zipBlob = await zip.generateAsync({
|
||||
type: 'blob',
|
||||
compression: 'DEFLATE',
|
||||
compressionOptions: {
|
||||
level: 6 // 中等压缩级别,平衡速度和大小
|
||||
}
|
||||
});
|
||||
|
||||
updateDownloadProgress('batch_all', 95, true);
|
||||
|
||||
// 下载 ZIP 文件
|
||||
saveAs(zipBlob, `${orderNo}_资源文件.zip`);
|
||||
updateDownloadProgress('batch_all', 100, false);
|
||||
|
||||
// 清理进度条
|
||||
const totalTime = ((Date.now() - startTime) / 1000).toFixed(1);
|
||||
message.success(`✅ 成功打包下载 ${successCount} 个文件,${failureCount} 个失败,耗时 ${totalTime}秒`);
|
||||
console.log(`✅ ZIP 下载完成: 成功=${successCount}, 失败=${failureCount}, 耗时=${totalTime}s`);
|
||||
|
||||
// 清理进度
|
||||
setTimeout(() => {
|
||||
removeDownloadProgress('batch_all');
|
||||
}, 500);
|
||||
|
||||
// 提示用户
|
||||
const message = `✅ 批量下载已启动!\n\n📦 文件数: ${successCount}/${resources.length}\n⏱️ 耗时: ${totalTime}s\n\n📋 所有文件并发下载中,请检查浏览器下载列表\n💡 如果文件过多,建议后台运行浏览器以加快下载`;
|
||||
console.log(`🎉 ${message}`);
|
||||
alert(message);
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ Batch download failed:`, error);
|
||||
|
||||
// 检查具体错误信息
|
||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||
if (errorMsg.includes('无效') || errorMsg.includes('为空')) {
|
||||
alert(`⚠️ 文件获取失败!\n\n${errorMsg}\n\n💡 请检查订单资源是否存在`);
|
||||
} else {
|
||||
alert('批量下载失败,请重试');
|
||||
}
|
||||
|
||||
console.error(`❌ ZIP 打包失败:`, error);
|
||||
message.error('打包下载失败,请重试');
|
||||
removeDownloadProgress('batch_all');
|
||||
} finally {
|
||||
setBatchDownloading(false);
|
||||
@@ -362,6 +389,37 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 删除按钮 - 左上角 */}
|
||||
<Popconfirm
|
||||
title="确定删除这个文件吗?"
|
||||
onConfirm={async (e) => {
|
||||
e?.stopPropagation();
|
||||
if (item.id) {
|
||||
await handleDeleteFile(item.id);
|
||||
}
|
||||
}}
|
||||
okText="确定"
|
||||
cancelText="取消"
|
||||
placement="bottomRight"
|
||||
>
|
||||
<Button
|
||||
type="primary"
|
||||
danger
|
||||
size="small"
|
||||
icon={<DeleteOutlined />}
|
||||
title="删除"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '4px',
|
||||
left: '4px',
|
||||
zIndex: 10,
|
||||
opacity: 0.9
|
||||
}}
|
||||
/>
|
||||
</Popconfirm>
|
||||
|
||||
{/* 下载按钮 - 右上角 */}
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
@@ -379,7 +437,7 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
||||
position: 'absolute',
|
||||
top: '4px',
|
||||
right: '4px',
|
||||
opacity: isDownloading ? 0.6 : 0.8
|
||||
opacity: isDownloading ? 0.6 : 0.9
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -428,22 +486,43 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
||||
{fileName}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
icon={<DownloadOutlined />}
|
||||
loading={isDownloading}
|
||||
disabled={isDownloading}
|
||||
title={isDownloading ? `下载中... ${downloadState?.progress || 0}%` : '下载'}
|
||||
onClick={async () => {
|
||||
if (item && !isDownloading) {
|
||||
await handleDownload(item, fileName);
|
||||
}
|
||||
}}
|
||||
style={{ marginLeft: '8px' }}
|
||||
>
|
||||
{isDownloading ? `下载中 ${downloadState?.progress || 0}%` : '下载'}
|
||||
</Button>
|
||||
<Space>
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
icon={<DownloadOutlined />}
|
||||
loading={isDownloading}
|
||||
disabled={isDownloading}
|
||||
title={isDownloading ? `下载中... ${downloadState?.progress || 0}%` : '下载'}
|
||||
onClick={async () => {
|
||||
if (item && !isDownloading) {
|
||||
await handleDownload(item, fileName);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{isDownloading ? `下载中 ${downloadState?.progress || 0}%` : '下载'}
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确定删除这个视频吗?"
|
||||
onConfirm={async () => {
|
||||
if (item.id) {
|
||||
await handleDeleteFile(item.id);
|
||||
}
|
||||
}}
|
||||
okText="确定"
|
||||
cancelText="取消"
|
||||
placement="bottomLeft"
|
||||
>
|
||||
<Button
|
||||
type="primary"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
title="删除视频"
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{/* 下载进度条 */}
|
||||
@@ -550,21 +629,21 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
||||
<Button
|
||||
key="batch-download"
|
||||
type="primary"
|
||||
icon={<DownloadOutlined />}
|
||||
icon={<FileZipOutlined />}
|
||||
loading={batchDownloading}
|
||||
disabled={resources.length === 0 || loading || batchDownloading}
|
||||
onClick={handleBatchDownload}
|
||||
title={batchDownloading ? `批量下载中...` : '下载全部文件'}
|
||||
title={batchDownloading ? `正在打包下载中...` : '批量下载为ZIP'}
|
||||
>
|
||||
{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)`;
|
||||
if (batchProgress) {
|
||||
return `打包中... ${batchProgress.progress}%`;
|
||||
}
|
||||
return `下载中... ${batchDownloadProgress}%`;
|
||||
})() : '下载全部文件'}
|
||||
return `打包中... ${batchDownloadProgress}%`;
|
||||
})() : '批量下载'}
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
|
||||
Reference in New Issue
Block a user