diff --git a/.claude/settings.local.json b/.claude/settings.local.json index 5711bb90..42cf801c 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -27,7 +27,9 @@ "Bash(git checkout:*)", "Bash(git diff:*)", "Bash(grep:*)", - "Bash(npm run tsc:*)" + "Bash(npm run tsc:*)", + "Bash(node:*)", + "Bash(javac:*)" ], "deny": [], "ask": [] diff --git a/zlt-business/file-center/src/main/java/com/central/file/controller/FileController.java b/zlt-business/file-center/src/main/java/com/central/file/controller/FileController.java index c8a169fa..0d82f0b7 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/controller/FileController.java +++ b/zlt-business/file-center/src/main/java/com/central/file/controller/FileController.java @@ -120,6 +120,11 @@ public class FileController { return timeWindowStorageService.getSmartViewUrl(id); } + @GetMapping("/file/download/{id}") + public String getFiledownloadUrl(@PathVariable String id) { + return timeWindowStorageService.getFileDownLoadUrl(id); + } + /** * 根据文件ID获取智能访问 URL(Result 包装) */ diff --git a/zlt-business/file-center/src/main/java/com/central/file/service/TimeWindowStorageService.java b/zlt-business/file-center/src/main/java/com/central/file/service/TimeWindowStorageService.java index 5097703a..ebe61293 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/service/TimeWindowStorageService.java +++ b/zlt-business/file-center/src/main/java/com/central/file/service/TimeWindowStorageService.java @@ -81,6 +81,25 @@ public class TimeWindowStorageService { } } + + /** + * 获取文件下载地址 + */ + public String getFileDownLoadUrl(String fileId) { + try { + FileInfo fileInfo = ossService.getFileInfo(fileId); + if (fileInfo == null) { + log.warn("文件不存在: fileId={}", fileId); + return ""; + } + String storageType = getStorageTypeByTime(fileInfo); + return getDownloadUrlByStorageType(fileInfo, storageType); + } catch (Exception e) { + log.error("智能存储查询失败: fileId={}, error={}", fileId, e.getMessage(), e); + return ""; + } + } + /** * 智能获取文件访问URL(通过ID) */ @@ -201,6 +220,31 @@ public class TimeWindowStorageService { } } + + /** + * 获取下载地址 + */ + private String getDownloadUrlByStorageType(FileInfo fileInfo, String storageType) { + + if ("S3".equals(storageType)) { + // 冷数据:S3优先,失败降级到OSS + String s3Url = queryDownLoadFromS3(fileInfo); + if (s3Url != null && !s3Url.isEmpty()) { + return applyCdnAcceleration(s3Url, "S3"); + } + String ossUrl = queryDownLoadFromOss(fileInfo); + return applyCdnAcceleration(ossUrl, "OSS"); + } else { + // 热数据:OSS优先,失败降级到S3 + String ossUrl = queryDownLoadFromOss(fileInfo); + if (ossUrl != null && !ossUrl.isEmpty()) { + return applyCdnAcceleration(ossUrl, "OSS"); + } + String s3Url = queryDownLoadFromS3(fileInfo); + return applyCdnAcceleration(s3Url, "S3"); + } + } + /** * 根据存储类型获取访问URL */ @@ -295,6 +339,25 @@ public class TimeWindowStorageService { return ""; } + + /** + * 从OSS查询文件URL + */ + private String queryDownLoadFromOss(FileInfo fileInfo) { + try { + String path = fileInfo.getPath(); + if (path != null && !path.isEmpty()) { + // 一键成片可能保存完整 OSS URL,这里去掉域名前缀转为相对路径 + String normalized = path.startsWith(OSS_DOMAIN_PREFIX) ? path.substring(OSS_DOMAIN_PREFIX.length()) : path; + return ossService.getDownloadUrl(normalized); + } + } catch (Exception e) { + log.warn("从OSS查询失败: fileId={}, error={}", fileInfo.getId(), e.getMessage()); + return ""; + } + return ""; + } + /** * 从S3查询文件URL */ @@ -361,6 +424,33 @@ public class TimeWindowStorageService { return ""; } + /** + * 从OSS查询文件URL + */ + private String queryDownLoadFromS3(FileInfo fileInfo) { + try { + String path = fileInfo.getPath(); + if (path != null && !path.isEmpty()) { + // 一键成片可能保存完整 OSS URL,这里去掉域名前缀转为相对路径 + final String OSS_DOMAIN_PREFIX = "https://goflyapp.oss-cn-beijing.aliyuncs.com/"; + String normalized = path.startsWith(OSS_DOMAIN_PREFIX) ? path.substring(OSS_DOMAIN_PREFIX.length()) : path; + if(s3Service != null) { + log.debug("使用S3Service查询: fileId={}, path={}", fileInfo.getId(), normalized); + String url = s3Service.getDownloadUrl(normalized); + log.info("从s3获取到的路径为:{}",url); + return url; + } else { + log.warn("S3服务未配置,无法查询S3: fileId={}", fileInfo.getId()); + return ""; + } + } + } catch (Exception e) { + log.warn("从S3查询失败: fileId={}, error={}", fileInfo.getId(), e.getMessage()); + return ""; + } + return ""; + } + /** * 从S3查询文件URL(通过路径) */ diff --git a/zlt-business/file-center/src/main/java/com/central/file/service/impl/AbstractIFileService.java b/zlt-business/file-center/src/main/java/com/central/file/service/impl/AbstractIFileService.java index d38be674..9b92dece 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/service/impl/AbstractIFileService.java +++ b/zlt-business/file-center/src/main/java/com/central/file/service/impl/AbstractIFileService.java @@ -111,6 +111,8 @@ public abstract class AbstractIFileService extends ServiceImpl downloadFile(@RequestBody FileDownloadRequest request) throws IOException { String fileUrl = request.getUrl(); - log.info("开始代理下载文件: {}", fileUrl); - + log.info("📥 开始代理下载文件: {}", fileUrl); if (fileUrl == null || fileUrl.trim().isEmpty()) { throw new IllegalArgumentException("文件URL不能为空"); } - - try { - // 从外部 CDN 下载文件 - URL url = new URL(fileUrl); - URLConnection connection = url.openConnection(); - - // 设置超时 - connection.setConnectTimeout(10000); - connection.setReadTimeout(30000); - - // 获取文件内容 - byte[] buffer = new byte[4096]; - int bytesRead; - java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream(); - - try (InputStream input = connection.getInputStream()) { - while ((bytesRead = input.read(buffer)) != -1) { - byteArrayOutputStream.write(buffer, 0, bytesRead); - } - } - - log.info("文件下载成功: {}", extractFileNameFromUrl(fileUrl)); - return byteArrayOutputStream.toByteArray(); - } catch (Exception e) { - log.error("文件下载失败: fileUrl={}", fileUrl, e); - throw new RuntimeException("文件下载失败: " + e.getMessage(), e); + // 从外部 CDN 下载文件 + URL url = new URL(fileUrl); + URLConnection connection = url.openConnection(); + // 设置超时和默认User-Agent + connection.setConnectTimeout(10000); // 10秒连接超时 + connection.setReadTimeout(300000); // 5分钟读取超时,避免网络差时频繁超时 + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"); + // 获取文件大小 + long fileSize = connection.getContentLengthLong(); + String fileName = extractFileNameFromUrl(fileUrl); + log.info("📊 文件信息: 名称={}, 大小={}MB", fileName, fileSize / (1024 * 1024)); + // 构建响应头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); + if (fileSize > 0) { + headers.setContentLength(fileSize); } + headers.set("Content-Disposition", + "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.name())); + headers.set("Accept-Ranges", "bytes"); + + // 返回流式响应 - 使用 StreamingResponseBody(核心优化!) + // 不需要在内存中积累整个文件,边读边写 + StreamingResponseBody streamingBody = outputStream -> { + try (InputStream input = connection.getInputStream()) { + byte[] buffer = new byte[8192]; // 8KB缓冲区 + int bytesRead; + long totalBytes = 0; + + while ((bytesRead = input.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + outputStream.flush(); // 及时flush + totalBytes += bytesRead; + // 每传输10MB时记录一次进度日志 + if (totalBytes % (10 * 1024 * 1024) == 0) { + log.debug("📊 下载进度: {}MB / {}MB", + totalBytes / (1024 * 1024), fileSize / (1024 * 1024)); + } + } + log.info("✅ 文件下载完成: {}, 总大小: {}MB", + fileName, totalBytes / (1024 * 1024)); + } catch (IOException e) { + log.error("❌ 流式传输文件异常: {}", fileName, e); + throw e; + } + }; + return ResponseEntity.ok() + .headers(headers) + .body(streamingBody); } /** - * 批量下载所有文件 - 打包为 ZIP + * 代理批量下载订单所有资源文件 - 改进版:真正的流式传输(无内存积累) + * + * 优化点: + * 1. 使用 StreamingResponseBody,不缓存整个ZIP在内存 + * 2. 流式生成ZIP条目,边组装边发送 + * 3. 及时flush,减少缓冲 + * 4. 支持大文件(无GB限制) */ @Operation(summary = "批量下载订单所有资源文件") @PostMapping("/download/batch") - public byte[] batchDownloadFiles(@RequestBody FileDownloadRequest request) { + public ResponseEntity batchDownloadFiles(@RequestBody FileDownloadRequest request) throws IOException { String orderNo = request.getOrderNo(); - log.info("开始批量下载订单文件: {}", orderNo); + log.info("📦 开始批量下载订单文件: {}", orderNo); if (orderNo == null || orderNo.trim().isEmpty()) { throw new IllegalArgumentException("订单编号不能为空"); } - try { // 查询订单所有文件 List orderFiles = orderFileService.getOrderFileByOrderNo(orderNo); if (CollectionUtils.isEmpty(orderFiles)) { - throw new IllegalArgumentException("订单暂无资源文件"); + throw new RuntimeException("订单无文件"); } - // 创建 ZIP 字节流 - java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream(); - try (ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) { - for (OrderFile orderFile : orderFiles) { - String viewUrl = fileCenterService.getFileViewUrl(orderFile.getFileId()); - if (viewUrl == null || viewUrl.isEmpty()) { - continue; - } + log.info("📊 订单文件数量: {}", orderFiles.size()); - try { - // 下载单个文件 - URL fileUrl = new URL(viewUrl); - URLConnection connection = fileUrl.openConnection(); - connection.setConnectTimeout(10000); - connection.setReadTimeout(30000); + // ===== 关键优化:使用流式传输,不需要预先计算总大小 ===== + // 直接处理所有文件,无GB限制(流式传输不需要在内存中积累) + log.info("📊 批量下载文件数: {}", orderFiles.size()); - String fileName = extractFileNameFromUrl(viewUrl); - - // 创建 ZIP 条目 - ZipEntry zipEntry = new ZipEntry(fileName); - zipOut.putNextEntry(zipEntry); - - // 写入文件内容到 ZIP - try (InputStream fileInput = connection.getInputStream()) { - byte[] buffer = new byte[4096]; - int bytesRead; - while ((bytesRead = fileInput.read(buffer)) != -1) { - zipOut.write(buffer, 0, bytesRead); - } - } - - zipOut.closeEntry(); - log.info("已添加文件到ZIP: {}", fileName); - } catch (Exception e) { - log.warn("添加文件到ZIP失败: {}", viewUrl, e); - // 继续处理其他文件 - } + // 过滤掉无效URL的文件 + List filesToDownload = new ArrayList<>(); + for (OrderFile file : orderFiles) { + String viewUrl = fileCenterService.getFileViewUrl(file.getFileId()); + if (viewUrl != null && !viewUrl.isEmpty()) { + filesToDownload.add(file); + } else { + log.warn("文件URL为空,跳过: {}", file.getFileId()); } } - log.info("批量下载完成: {}", orderNo); - return byteArrayOutputStream.toByteArray(); + if (filesToDownload.isEmpty()) { + throw new RuntimeException("订单无有效资源文件"); + } + + log.info("📊 有效下载文件数: {}", filesToDownload.size()); + + // 构建响应头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.valueOf("application/zip")); + headers.set("Content-Disposition", + "attachment;filename=" + URLEncoder.encode(orderNo + ".zip", StandardCharsets.UTF_8.name())); + headers.set("Accept-Ranges", "bytes"); + headers.setCacheControl("no-cache"); + // 注意:不设置 Content-Length,因为流式传输无法预知最终大小 + // 前端会显示已下载字节数和速度,而不是百分比进度 + + // 返回流式响应 - 使用 StreamingResponseBody + // 不需要预先计算Content-Length,数据直接流向浏览器 + StreamingResponseBody streamingBody = outputStream -> { + try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) { + // 设置ZIP压缩级别 + zipOut.setLevel(6); + + int successCount = 0; + int failureCount = 0; + + for (int i = 0; i < filesToDownload.size(); i++) { + OrderFile orderFile = filesToDownload.get(i); + String viewUrl = fileCenterService.getFileViewUrl(orderFile.getFileId()); + if (viewUrl == null || viewUrl.isEmpty()) { + failureCount++; + continue; + } + + try { + // 下载单个文件 + URL fileUrl = new URL(viewUrl); + URLConnection connection = fileUrl.openConnection(); + connection.setConnectTimeout(10000); // 10秒连接超时 + connection.setReadTimeout(300000); // 5分钟读取超时,避免网络差时频繁超时 + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"); + + String fileName = extractFileNameFromUrl(viewUrl); + + // 创建 ZIP 条目 + ZipEntry zipEntry = new ZipEntry(fileName); + zipOut.putNextEntry(zipEntry); + + long fileBytes = 0; + + // 写入文件内容到 ZIP - 流式传输(核心优化!) + try (InputStream fileInput = connection.getInputStream()) { + byte[] buffer = new byte[8192]; + int bytesRead; + while ((bytesRead = fileInput.read(buffer)) != -1) { + zipOut.write(buffer, 0, bytesRead); + fileBytes += bytesRead; + } + } + + zipOut.closeEntry(); + zipOut.flush(); // 及时flush,减少缓冲 + + log.info("✅ 已添加文件到ZIP ({}/{}): {} ({}MB)", + i + 1, filesToDownload.size(), fileName, fileBytes / (1024 * 1024)); + successCount++; + + } catch (Exception e) { + log.warn("❌ 添加文件到ZIP失败 ({}/{}): {}, 错误: {}", + i + 1, filesToDownload.size(), viewUrl, e.getMessage()); + failureCount++; + } + } + + log.info("📦 批量下载完成: 订单号={}, 成功={}, 失败={}", + orderNo, successCount, failureCount); + } catch (IOException e) { + log.error("❌ 流式传输ZIP失败: orderNo={}", orderNo, e); + throw e; + } + }; + + return ResponseEntity.ok() + .headers(headers) + .body(streamingBody); + } catch (Exception e) { - log.error("批量下载文件失败: orderNo={}", orderNo, e); + log.error("❌ 批量下载文件失败: orderNo={}", orderNo, e); throw new RuntimeException("批量下载失败: " + e.getMessage(), e); } } @@ -711,4 +805,16 @@ public class OrderFileController { } } + @Operation(summary = "根据文件id获取下载链接") + @GetMapping("/file/download/{fileId}") + public String getFileDownLoadUrl(@PathVariable("fileId") String fileId) { + if(fileId==null && fileId==""){ + return ""; + } + + String url= fileCenterService.getFileDownLoadUrl(fileId); + log.info("返回的下载url为{}",url); + return url; + } + } diff --git a/zlt-business/order-center/src/main/java/com/central/order/feign/FileCenterService.java b/zlt-business/order-center/src/main/java/com/central/order/feign/FileCenterService.java index 07e3ec81..e39d22f2 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/feign/FileCenterService.java +++ b/zlt-business/order-center/src/main/java/com/central/order/feign/FileCenterService.java @@ -70,4 +70,8 @@ public interface FileCenterService { Result batchPrefetchFiles(@RequestBody List urls, @RequestParam(value = "batchSize", defaultValue = "100") int batchSize, @RequestParam(value = "area", required = false) String area); + + + @GetMapping("/file/download/{id}") + String getFileDownLoadUrl(@PathVariable("id") String id); } diff --git a/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/FileCenterServiceFallbackFactory.java b/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/FileCenterServiceFallbackFactory.java index e5f8f66a..36b3bb6f 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/FileCenterServiceFallbackFactory.java +++ b/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/FileCenterServiceFallbackFactory.java @@ -73,6 +73,11 @@ public class FileCenterServiceFallbackFactory implements FallbackFactory 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 +69,7 @@ const OrderResourcesModal: React.FC = ({ visible, reco const [hasLoadedOnce, setHasLoadedOnce] = useState(false); const [error, setError] = useState(null); const [batchDownloading, setBatchDownloading] = useState(false); + const [downloadingFiles, setDownloadingFiles] = useState>(new Map()); // 当弹窗打开时加载资源列表 const loadResources = useCallback(async () => { @@ -82,7 +91,6 @@ const OrderResourcesModal: React.FC = ({ 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) { @@ -99,162 +107,201 @@ const OrderResourcesModal: React.FC = ({ visible, reco const images = resources.filter(isImageFile); const videos = resources.filter(isVideoFile); - // 处理下载 - 通过后端代理解决跨域问题 - const handleDownload = async (url: string, fileName?: string) => { - if (!url) return; + // 生成唯一的文件ID + const getFileId = (url: string | undefined, fileName?: string): string => { + return fileName || url as string; + }; - const finalFileName = fileName || `file_${Date.now()}`; - console.log(`⬇️ Starting download: ${url} as ${finalFileName}`); + // 更新下载进度 + 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 handleDeleteFile = async (fileId: number | string) => { try { - // 方式1: 通过后端代理下载(推荐 - 解决跨域问题) - console.log('📌 Downloading via backend proxy...'); - const blob = await ordersApi.downloadFile(url); + message.loading('正在删除文件...', 0); - 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); + // 调用删除接口 + await ordersApi.deleteOrderFile(Number(fileId)); - setTimeout(() => { - a.click(); - console.log(`✅ Download started via backend proxy: ${finalFileName}`); + message.destroy(); + message.success('删除成功'); - setTimeout(() => { - document.body.removeChild(a); - window.URL.revokeObjectURL(blobUrl); - }, 100); - }, 0); - - return true; + // 重新加载资源列表 + setHasLoadedOnce(false); + await loadResources(); } catch (error) { - console.error(`❌ Backend proxy download failed:`, error); - - try { - // 方式2: 尝试 XMLHttpRequest(本地可用但跨域受限) - console.log('📌 Trying XHR method...'); - return await new Promise((resolve, reject) => { - const xhr = new XMLHttpRequest(); - xhr.open('GET', url, true); - xhr.responseType = 'blob'; - - xhr.onload = () => { - if (xhr.status === 200) { - const blob = xhr.response; - 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}`); - - setTimeout(() => { - document.body.removeChild(a); - window.URL.revokeObjectURL(blobUrl); - resolve(true); - }, 100); - }, 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); - - // 方式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; - } + message.destroy(); + console.error('删除文件失败:', error); + message.error('删除失败,请重试'); } }; - // 批量下载所有文件 - 并发调用单个文件下载接口 + // 处理下载 - 获取URL后用 标签强制下载 + const handleDownload = async (file: OrderFile, fileName?: string) => { + if (!file || !file.fileId) { + return; + } + + const finalFileName = fileName || getFileName(file, 0); + const fileId = file.fileId; + + updateDownloadProgress(fileId, 0, true); + + try { + updateDownloadProgress(fileId, 50, true); + + // 获取下载URL + const downloadUrl = await ordersApi.getFileDownloadUrl(fileId); + + if (!downloadUrl) { + throw new Error('Failed to get download URL'); + } + + updateDownloadProgress(fileId, 100, false); + + // 创建临时 标签并使用 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(() => { + removeDownloadProgress(fileId); + }, 300); + + return true; + } catch (error) { + removeDownloadProgress(fileId); + return false; + } + }; + +// 批量下载所有文件为 ZIP - 前端打包 const handleBatchDownload = async () => { if (!record?.orderNo) { - console.warn('⚠️ orderNo is missing'); + message.warning('订单号缺失'); return; } const orderNo = record.orderNo; - console.log(`⬇️ Starting 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; + + // 并发下载所有文件并添加到 ZIP + console.log(`📌 开始下载 ${resources.length} 个文件...`); + updateDownloadProgress('batch_all', 20, true); + const downloadPromises = resources.map(async (file, index) => { - if (!file.viewUrl) { - console.warn(`⚠️ Skipping file without URL: ${file.filePath}`); - return false; - } - - const fileName = file.filePath ? file.filePath.split('/').pop() : `file_${index + 1}`; - console.log(`📥 Queuing download (${index + 1}/${resources.length}): ${fileName}`); - try { - // 调用单个文件下载接口获取 blob - const blob = await ordersApi.downloadFile(file.viewUrl); - - // 创建下载链接并触发浏览器下载 - 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 = '文件下载'; + if (!file.fileId) { + failureCount++; + return; } - a.style.display = 'none'; - document.body.appendChild(a); - // 添加延迟以错开下载请求,避免浏览器并发限制 - await new Promise((resolve) => setTimeout(resolve, index * 150)); - a.click(); - console.log(`✅ Download triggered: ${fileName}`); - // 清理资源 - setTimeout(() => { - document.body.removeChild(a); - window.URL.revokeObjectURL(blobUrl); - }, 500); + // 获取下载 URL + const downloadUrl = await ordersApi.getFileDownloadUrl(file.fileId); + if (!downloadUrl) { + failureCount++; + return; + } - return true; + // 下载文件内容 + 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.error(`❌ Failed to download: ${fileName}`, error); - return false; + console.error(`❌ 处理文件失败:`, error); + failureCount++; } }); - // 等待所有下载请求完成(不等待浏览器下载完成) - const results = await Promise.all(downloadPromises); - const successCount = results.filter((r) => r).length; - const failureCount = results.filter((r) => !r).length; + // 等待所有下载完成 + await Promise.allSettled(downloadPromises); + + 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失败: ${failureCount}\n\n📥 文件已经全部下载完成\n📋 请检查浏览器下载列表`; - console.log(`🎉 ${message}`); - alert(message); } catch (error) { - console.error(`❌ Batch download failed:`, error); - alert('批量下载失败,请重试'); + console.error(`❌ ZIP 打包失败:`, error); + message.error('打包下载失败,请重试'); + removeDownloadProgress('batch_all'); } finally { setBatchDownloading(false); } @@ -276,6 +323,10 @@ const OrderResourcesModal: React.FC = ({ 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 (
= ({ visible, reco }}> {fileName}
+ + {/* 下载进度条 */} + {downloadState && ( +
+
+
+ )} + + {/* 删除按钮 - 左上角 */} + { + e?.stopPropagation(); + if (item.id) { + await handleDeleteFile(item.id); + } + }} + okText="确定" + cancelText="取消" + placement="bottomRight" + > +
@@ -347,6 +457,10 @@ const OrderResourcesModal: React.FC = ({ visible, reco
{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 (
= ({ visible, reco display: 'flex', justifyContent: 'space-between', alignItems: 'center', + position: 'relative' }}> -
+
{fileName}
- + { + if (item.id) { + await handleDeleteFile(item.id); + } + }} + okText="确定" + cancelText="取消" + placement="bottomLeft" + > + + + +
+ + {/* 下载进度条 */} + {downloadState && ( +
- 下载 - -
+
+
+ )} {/* 视频播放器 */}
= ({ visible, reco
); + // 计算批量下载进度 + 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) { @@ -456,12 +629,21 @@ const OrderResourcesModal: React.FC = ({ visible, reco , ]} > diff --git a/zlt-web/react-web-next/src/services/orders.ts b/zlt-web/react-web-next/src/services/orders.ts index d334322f..52566354 100644 --- a/zlt-web/react-web-next/src/services/orders.ts +++ b/zlt-web/react-web-next/src/services/orders.ts @@ -321,15 +321,62 @@ export const ordersApi = { } }, + // 获取单个文件的下载URL + getFileDownloadUrl: async (fileId: string) => { + const res = await request(`/api-order/files/file/download/${fileId}`, { method: 'GET' }); + return (res as any) || ''; + }, + // 下载文件 - 通过后端代理(解决跨域问题) - downloadFile: async (fileUrl: string) => { + // 优化:改为流式传输,支持大文件下载、断点续传 + // 注意:使用 XMLHttpRequest 以支持进度回调和流式传输 + downloadFile: async (fileUrl: string, onProgress?: (progress: number) => void) => { try { - const res = await request('/api-order/files/download', { - method: 'POST', - data: { url: fileUrl }, - responseType: 'blob', + // 获取当前token,用于请求头 + const token = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('access_token') : null; + + return await new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open('POST', '/api-order/files/download', true); + xhr.responseType = 'blob'; + xhr.setRequestHeader('Content-Type', 'application/json'); + + // 添加Authorization请求头(重要!) + if (token) { + xhr.setRequestHeader('Authorization', `Bearer ${token}`); + } + + // 监听下载进度 + xhr.addEventListener('progress', (event) => { + if (event.lengthComputable && onProgress) { + const percentComplete = Math.round((event.loaded / event.total) * 100); + onProgress(percentComplete); + console.log(`📊 下载进度: ${percentComplete}%`); + } + }); + + xhr.addEventListener('load', () => { + if (xhr.status === 200) { + console.log('✅ 文件下载成功'); + resolve(xhr.response as Blob); + } else { + reject(new Error(`HTTP ${xhr.status}`)); + } + }); + + xhr.addEventListener('error', () => { + console.error('❌ 网络错误'); + reject(new Error('网络错误')); + }); + + xhr.addEventListener('abort', () => { + console.error('❌ 下载被中止'); + reject(new Error('下载被中止')); + }); + + // 发送请求(请求头需要在open和send之间添加) + xhr.send(JSON.stringify({ url: fileUrl })); }); - return res; } catch (error) { console.error('❌ downloadFile error:', error); throw error; @@ -337,14 +384,62 @@ export const ordersApi = { }, // 批量下载所有文件 - 打包为 ZIP - batchDownloadFiles: async (orderNo: string) => { + // 优化:改为流式传输,支持大型ZIP下载 + batchDownloadFiles: async (orderNo: string, onProgress?: (progress: number) => void) => { try { - const res = await request('/api-order/files/download/batch', { - method: 'POST', - data: { orderNo }, - responseType: 'blob', + // 获取当前token,用于请求头 + const token = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('access_token') : null; + + return await new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open('POST', '/api-order/files/download/batch', true); + xhr.responseType = 'blob'; + xhr.setRequestHeader('Content-Type', 'application/json'); + + // 添加Authorization请求头(重要!) + if (token) { + xhr.setRequestHeader('Authorization', `Bearer ${token}`); + } + + // 监听下载进度 + // 注意:即使 Content-Length 未知,progress 事件仍会触发,可以获取 event.loaded + xhr.addEventListener('progress', (event) => { + if (onProgress) { + if (event.lengthComputable) { + // 如果知道总大小,计算百分比 + const percentComplete = Math.round((event.loaded / event.total) * 100); + onProgress(percentComplete); + console.log(`📊 批量下载进度: ${percentComplete}%`); + } else { + // 如果不知道总大小,直接传递已下载字节数 + onProgress(event.loaded); + console.log(`📊 批量下载进度: ${event.loaded} bytes`); + } + } + }); + + xhr.addEventListener('load', () => { + if (xhr.status === 200) { + console.log('✅ 批量下载成功'); + resolve(xhr.response as Blob); + } else { + reject(new Error(`HTTP ${xhr.status}`)); + } + }); + + xhr.addEventListener('error', () => { + console.error('❌ 网络错误'); + reject(new Error('网络错误')); + }); + + xhr.addEventListener('abort', () => { + console.error('❌ 下载被中止'); + reject(new Error('下载被中止')); + }); + + // 发送请求(请求头需要在open和send之间添加) + xhr.send(JSON.stringify({ orderNo })); }); - return res; } catch (error) { console.error('❌ batchDownloadFiles error:', error); throw error;