!61 feat: 1:资源列表批量下载优化,可以下载为zip

Merge pull request !61 from 鸭先知/feature_dzc
This commit is contained in:
2025-11-06 11:30:05 +00:00
committed by Gitee
4 changed files with 176 additions and 96 deletions
@@ -230,7 +230,7 @@ public class TimeWindowStorageService {
// 冷数据:S3优先,失败降级到OSS // 冷数据:S3优先,失败降级到OSS
String s3Url = queryDownLoadFromS3(fileInfo); String s3Url = queryDownLoadFromS3(fileInfo);
if (s3Url != null && !s3Url.isEmpty()) { if (s3Url != null && !s3Url.isEmpty()) {
return s3Url; return applyCdnAcceleration(s3Url, "S3");
} }
String ossUrl = queryDownLoadFromOss(fileInfo); String ossUrl = queryDownLoadFromOss(fileInfo);
return applyCdnAcceleration(ossUrl, "OSS"); return applyCdnAcceleration(ossUrl, "OSS");
@@ -241,7 +241,7 @@ public class TimeWindowStorageService {
return applyCdnAcceleration(ossUrl, "OSS"); return applyCdnAcceleration(ossUrl, "OSS");
} }
String s3Url = queryDownLoadFromS3(fileInfo); String s3Url = queryDownLoadFromS3(fileInfo);
return s3Url; return applyCdnAcceleration(s3Url, "S3");
} }
} }
@@ -137,7 +137,7 @@ public class S3Template implements InitializingBean {
*/ */
public String getDownloadUrl(String objectName) { public String getDownloadUrl(String objectName) {
// 1. 入参校验:避免空指针和无效路径(关键:防止后续 NPE) // 1. 入参校验:避免空指针和无效路径(关键:防止后续 NPE)
if (!StringUtils.hasText(objectName)) { /*if (!StringUtils.hasText(objectName)) {
throw new IllegalArgumentException("S3 ObjectKey 不能为空!"); throw new IllegalArgumentException("S3 ObjectKey 不能为空!");
} }
String bucketName = fileProperties.getS3().getBucketName(); String bucketName = fileProperties.getS3().getBucketName();
@@ -170,9 +170,7 @@ public class S3Template implements InitializingBean {
ResponseHeaderOverrides presetHeaders = new ResponseHeaderOverrides(); ResponseHeaderOverrides presetHeaders = new ResponseHeaderOverrides();
presetHeaders.setContentDisposition("attachment;filename*=UTF-8''" + encodedFilename); presetHeaders.setContentDisposition("attachment;filename*=UTF-8''" + encodedFilename);
presetHeaders.setContentType("application/octet-stream"); presetHeaders.setContentType("application/octet-stream");
presetHeaders.setCacheControl("no-cache, no-store, must-revalidate");
req.setResponseHeaders(presetHeaders); req.setResponseHeaders(presetHeaders);
// 6. 生成并返回下载 URL // 6. 生成并返回下载 URL
return amazonS3.generatePresignedUrl(req).toString(); return amazonS3.generatePresignedUrl(req).toString();
@@ -182,7 +180,9 @@ public class S3Template implements InitializingBean {
} catch (Exception e) { } catch (Exception e) {
// 捕获 S3 签名/网络/权限异常,包装后抛出(便于排查) // 捕获 S3 签名/网络/权限异常,包装后抛出(便于排查)
throw new RuntimeException("生成 S3 强制下载 URL 失败!objectName=" + objectName, e); throw new RuntimeException("生成 S3 强制下载 URL 失败!objectName=" + objectName, e);
} }*/
String url = getViewUrlNoExpires(objectName);
return url+"?"+"response-content-disposition=attachment";
} }
/** /**
+1
View File
@@ -24,6 +24,7 @@
"antd": "^4.20.0", "antd": "^4.20.0",
"file-saver": "^2.0.5", "file-saver": "^2.0.5",
"jsencrypt": "^3.5.4", "jsencrypt": "^3.5.4",
"jszip": "^3.10.1",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"moment": "^2.29.0", "moment": "^2.29.0",
"react": "^17.0.2", "react": "^17.0.2",
@@ -1,9 +1,11 @@
import React, { useState, useCallback } from 'react'; import React, { useState, useCallback } from 'react';
import { Modal, Spin, Empty, Image, Badge, Tabs, Space, Button, Tooltip } from 'antd'; import { Modal, Spin, Empty, Image, Badge, Tabs, Space, Button, Tooltip, message, Popconfirm } from 'antd';
import { DownloadOutlined, PictureOutlined, PlayCircleOutlined } from '@ant-design/icons'; import { DownloadOutlined, PictureOutlined, PlayCircleOutlined, FileZipOutlined, DeleteOutlined } from '@ant-design/icons';
import { ordersApi } from '@/services/orders'; import { ordersApi } from '@/services/orders';
import type { OrderItem } from '@/services/orders'; import type { OrderItem } from '@/services/orders';
import {dateFormatterMap} from "@ant-design/pro-components"; import {dateFormatterMap} from "@ant-design/pro-components";
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
interface OrderFile { interface OrderFile {
id?: number | string; 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> 标签强制下载 // 处理下载 - 获取URL后用 <a> 标签强制下载
const handleDownload = async (file: OrderFile, fileName?: string) => { const handleDownload = async (file: OrderFile, fileName?: string) => {
if (!file || !file.fileId) { if (!file || !file.fileId) {
@@ -171,109 +194,113 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
} }
}; };
// 批量下载所有文件 - 优化:直接获取每个文件的下载URL,由浏览器并发下载 // 批量下载所有文件为 ZIP - 前端打包
// 优势:充分利用用户网络带宽,无需后端生成ZIP,下载速度更快
const handleBatchDownload = async () => { const handleBatchDownload = async () => {
if (!record?.orderNo) { if (!record?.orderNo) {
console.warn('⚠️ orderNo is missing'); message.warning('订单号缺失');
return; return;
} }
const orderNo = record.orderNo; const orderNo = record.orderNo;
console.log(`📦 Starting optimized batch download for order: ${orderNo}`); console.log(`📦 开始批量下载并打包为 ZIP: ${orderNo}`);
console.log(`📊 Total files to download: ${resources.length}`); console.log(`📊 总文件数: ${resources.length}`);
setBatchDownloading(true); setBatchDownloading(true);
const startTime = Date.now(); const startTime = Date.now();
try { try {
// 创建虚拟进度条项 // 创建 JSZip 实例
const zip = new JSZip();
// 更新进度
updateDownloadProgress('batch_all', 0, true); updateDownloadProgress('batch_all', 0, true);
updateDownloadProgress('batch_all', 10, true); updateDownloadProgress('batch_all', 10, true);
let successCount = 0; let successCount = 0;
let failureCount = 0; let failureCount = 0;
console.log(`📌 Fetching download URLs for ${resources.length} files...`); // 并发下载所有文件并添加到 ZIP
console.log(`📌 开始下载 ${resources.length} 个文件...`);
updateDownloadProgress('batch_all', 20, true); updateDownloadProgress('batch_all', 20, true);
// 获取所有文件的下载URL const downloadPromises = resources.map(async (file, index) => {
const fileDownloadMap = new Map<string, { file: OrderFile; url: string }>();
// 分批获取URL,避免过多并发请求
for (let i = 0; i < resources.length; i++) {
const file = resources[i];
try { try {
const downloadUrl = await ordersApi.getFileDownloadUrl(file.fileId!); if (!file.fileId) {
if (downloadUrl) {
fileDownloadMap.set(file.fileId!, { file, url: downloadUrl });
successCount++;
} else {
failureCount++; 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) { } catch (error) {
console.warn(`⚠️ Failed to get download URL for file ${file.fileId}:`, error); console.error(`❌ 处理文件失败:`, error);
failureCount++; 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); await Promise.allSettled(downloadPromises);
updateDownloadProgress('batch_all', 90, true);
const totalTime = ((Date.now() - startTime) / 1000).toFixed(1); if (successCount === 0) {
console.log(`✅ Batch download completed: ${successCount} files triggered, ${failureCount} failed, cost ${totalTime}s`); 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); 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(() => { setTimeout(() => {
removeDownloadProgress('batch_all'); removeDownloadProgress('batch_all');
}, 500); }, 500);
// 提示用户
const message = `✅ 批量下载已启动!\n\n📦 文件数: ${successCount}/${resources.length}\n⏱️ 耗时: ${totalTime}s\n\n📋 所有文件并发下载中,请检查浏览器下载列表\n💡 如果文件过多,建议后台运行浏览器以加快下载`;
console.log(`🎉 ${message}`);
alert(message);
} catch (error) { } catch (error) {
console.error(`❌ Batch download failed:`, error); console.error(`❌ ZIP 打包失败:`, error);
message.error('打包下载失败,请重试');
// 检查具体错误信息
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'); removeDownloadProgress('batch_all');
} finally { } finally {
setBatchDownloading(false); setBatchDownloading(false);
@@ -362,6 +389,37 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
</div> </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 <Button
type="primary" type="primary"
size="small" size="small"
@@ -379,7 +437,7 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
position: 'absolute', position: 'absolute',
top: '4px', top: '4px',
right: '4px', right: '4px',
opacity: isDownloading ? 0.6 : 0.8 opacity: isDownloading ? 0.6 : 0.9
}} }}
/> />
</div> </div>
@@ -428,22 +486,43 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
{fileName} {fileName}
</span> </span>
</div> </div>
<Button <Space>
type="primary" <Button
size="small" type="primary"
icon={<DownloadOutlined />} size="small"
loading={isDownloading} icon={<DownloadOutlined />}
disabled={isDownloading} loading={isDownloading}
title={isDownloading ? `下载中... ${downloadState?.progress || 0}%` : '下载'} disabled={isDownloading}
onClick={async () => { title={isDownloading ? `下载中... ${downloadState?.progress || 0}%` : '下载'}
if (item && !isDownloading) { onClick={async () => {
await handleDownload(item, fileName); if (item && !isDownloading) {
} await handleDownload(item, fileName);
}} }
style={{ marginLeft: '8px' }} }}
> >
{isDownloading ? `下载中 ${downloadState?.progress || 0}%` : '下载'} {isDownloading ? `下载中 ${downloadState?.progress || 0}%` : '下载'}
</Button> </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> </div>
{/* 下载进度条 */} {/* 下载进度条 */}
@@ -550,21 +629,21 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
<Button <Button
key="batch-download" key="batch-download"
type="primary" type="primary"
icon={<DownloadOutlined />} icon={<FileZipOutlined />}
loading={batchDownloading} loading={batchDownloading}
disabled={resources.length === 0 || loading || batchDownloading} disabled={resources.length === 0 || loading || batchDownloading}
onClick={handleBatchDownload} onClick={handleBatchDownload}
title={batchDownloading ? `批量下载中...` : '下载全部文件'} title={batchDownloading ? `正在打包下载中...` : '批量下载为ZIP'}
> >
{batchDownloading ? (() => { {batchDownloading ? (() => {
const batchProgress = Array.from(downloadingFiles.values()).find( const batchProgress = Array.from(downloadingFiles.values()).find(
d => typeof d.fileId === 'string' && d.fileId === 'batch_all' d => typeof d.fileId === 'string' && d.fileId === 'batch_all'
); );
if (batchProgress && (batchProgress as any).downloadedMB) { if (batchProgress) {
return `下载中... ${(batchProgress as any).downloadedMB}MB (${(batchProgress as any).speed}MB/s)`; return `打包中... ${batchProgress.progress}%`;
} }
return `下载中... ${batchDownloadProgress}%`; return `打包中... ${batchDownloadProgress}%`;
})() : '下载全部文件'} })() : '批量下载'}
</Button>, </Button>,
]} ]}
> >