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

Merge pull request !60 from 鸭先知/feature_dzc
This commit is contained in:
2025-11-06 09:07:42 +00:00
committed by Gitee
15 changed files with 365 additions and 188 deletions
@@ -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 包装)
*/
@@ -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 s3Url;
}
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 s3Url;
}
}
/**
* 根据存储类型获取访问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(通过路径)
*/
@@ -111,6 +111,8 @@ public abstract class AbstractIFileService extends ServiceImpl<FileMapper, FileI
public abstract String getViewUrlByPath(String name);
public abstract String getDownloadUrl(String path);
@Override
public FileInfo getFileInfo(String id) {
return baseMapper.selectById(id);
@@ -55,6 +55,11 @@ public class CosService extends AbstractIFileService {
return "";
}
@Override
public String getDownloadUrl(String path) {
return "";
}
@Override
public String getZipViewUrlByPath(String name, String style) {
return "";
@@ -89,6 +89,11 @@ public class EnhancedS3Service extends AbstractIFileService {
}
}
@Override
public String getDownloadUrl(String path) {
return "";
}
@Override
public String getZipViewUrlByPath(String name, String style) {
// 实现压缩文件URL获取逻辑
@@ -51,6 +51,11 @@ public class FastdfsService extends AbstractIFileService {
return "";
}
@Override
public String getDownloadUrl(String path) {
return "";
}
@Override
public String getZipViewUrlByPath(String name, String style) {
return "";
@@ -86,6 +86,11 @@ public class OssService extends AbstractIFileService {
}
@Override
public String getDownloadUrl(String path) {
return ossTemplate.getDownloadUrl(path);
}
@Override
public String getZipViewUrlByPath(String path, String style) {
return ossTemplate.getViewUrl(path,style);
@@ -68,6 +68,11 @@ public class S3Service extends AbstractIFileService {
}
}
@Override
public String getDownloadUrl(String path) {
return s3Template.getDownloadUrl(path);
}
@Override
public String getZipViewUrlByPath(String name, String style) {
try {
@@ -26,12 +26,8 @@ import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
@@ -601,26 +597,20 @@ public class OrderFileController {
public ResponseEntity<StreamingResponseBody> downloadFile(@RequestBody FileDownloadRequest request) throws IOException {
String fileUrl = request.getUrl();
log.info("📥 开始代理下载文件: {}", fileUrl);
if (fileUrl == null || fileUrl.trim().isEmpty()) {
throw new IllegalArgumentException("文件URL不能为空");
}
// 从外部 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);
@@ -656,7 +646,6 @@ public class OrderFileController {
throw e;
}
};
return ResponseEntity.ok()
.headers(headers)
.body(streamingBody);
@@ -680,7 +669,6 @@ public class OrderFileController {
if (orderNo == null || orderNo.trim().isEmpty()) {
throw new IllegalArgumentException("订单编号不能为空");
}
try {
// 查询订单所有文件
List<OrderFile> orderFiles = orderFileService.getOrderFileByOrderNo(orderNo);
@@ -817,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;
}
}
@@ -70,4 +70,8 @@ public interface FileCenterService {
Result<Boolean> batchPrefetchFiles(@RequestBody List<String> 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);
}
@@ -73,6 +73,11 @@ public class FileCenterServiceFallbackFactory implements FallbackFactory<FileCen
return Result.failed("CDN批量预热文件失败: " + cause.getMessage());
}
@Override
public String getFileDownLoadUrl(String id) {
return "";
}
};
}
}
@@ -11,14 +11,18 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
/**
* cos 配置
@@ -168,6 +172,63 @@ public class OssTemplate implements InitializingBean {
return url.toString();
}
/**
* 获取下载地址
* @param objectName 对象名
* @return
*/
public String getDownloadUrl(String objectName) {
// 1. 入参校验:避免空指针和无效路径
if (!StringUtils.hasText(objectName)) {
throw new IllegalArgumentException("OSS ObjectKey 不能为空!");
}
String bucketName = fileProperties.getOss().getBucketName();
if (!StringUtils.hasText(bucketName)) {
throw new IllegalArgumentException("OSS Bucket 名称未配置!");
}
try {
// 2. 设置过期时间(线程安全,替代原 Calendar)
Instant expireInstant = Instant.now().plus(Duration.ofMinutes(DEFAULT_EXPIRE_TYPE));
Date expiration = Date.from(expireInstant);
// 3. 构建签名请求(核心:GET 方法用于下载)
GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(
bucketName,
objectName,
HttpMethod.GET // 明确 HTTP 方法,避免冲突
);
req.setExpiration(expiration);
// 4. 处理文件名:兼容中文/空格,避免下载乱码
String filename = Paths.get(objectName).getFileName().toString();
if (!StringUtils.hasText(filename)) {
throw new IllegalArgumentException("ObjectKey 格式错误,无法提取文件名:" + objectName);
}
// UTF-8 编码 + 替换空格为 %20(URL 标准编码)
String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name())
.replace("+", "%20");
// 5. 配置响应头:强制下载(核心需求)
ResponseHeaderOverrides headers = new ResponseHeaderOverrides();
// RFC 5987 标准格式:兼容所有浏览器(包括 IE)的中文文件名下载
headers.setContentDisposition("attachment;filename*=UTF-8''" + encodedFilename);
// 固定为二进制流:确保所有文件都触发下载(而非在线预览,符合你的需求)
// headers.setContentType("application/octet-stream");
req.setResponseHeaders(headers);
// 6. 生成并返回下载 URL
return ossClient.generatePresignedUrl(req).toString();
} catch (IllegalArgumentException e) {
// 入参错误直接抛出,上层可快速处理
throw e;
} catch (Exception e) {
// 捕获 OSS 签名/网络/权限异常,包装后抛出(便于上层排查)
throw new RuntimeException("生成 OSS 下载 URL 失败!objectName=" + objectName, e);
}
}
public void out(String objectName, OutputStream os) {
out(fileProperties.getOss().getBucketName(), objectName, os);
}
@@ -1,6 +1,7 @@
package com.central.oss.template;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.HttpMethod;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
@@ -8,10 +9,7 @@ import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.services.s3.model.*;
import com.amazonaws.util.IOUtils;
import com.central.oss.model.ObjectInfo;
import com.central.oss.properties.FileServerProperties;
@@ -21,13 +19,20 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
/**
* aws s3配置
@@ -125,6 +130,61 @@ public class S3Template implements InitializingBean {
return url.toString();
}
/**
* 获取下载地址
* @param objectName 对象名
* @return
*/
public String getDownloadUrl(String objectName) {
// 1. 入参校验:避免空指针和无效路径(关键:防止后续 NPE)
if (!StringUtils.hasText(objectName)) {
throw new IllegalArgumentException("S3 ObjectKey 不能为空!");
}
String bucketName = fileProperties.getS3().getBucketName();
if (!StringUtils.hasText(bucketName)) {
throw new IllegalArgumentException("S3 Bucket 名称未配置!");
}
try {
// 2. 过期时间:24小时(线程安全,替代 Calendar)
Instant expireInstant = Instant.now().plus(Duration.ofHours(24));
Date expiration = Date.from(expireInstant);
// 3. 构建 S3 签名请求
GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(
bucketName,
objectName,
HttpMethod.GET
);
req.setExpiration(expiration);
// 4. 处理文件名:兼容中文/空格/特殊字符
String filename = Paths.get(objectName).getFileName().toString();
if (!StringUtils.hasText(filename)) {
throw new IllegalArgumentException("ObjectKey 格式错误,无法提取文件名:" + objectName);
}
String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name())
.replace("+", "%20") // 空格转义为 %20(URL 标准)
.replace("*", "%2A"); // 星号转义(避免 URL 解析错误)
// 5. 核心:配置强制下载的响应头
ResponseHeaderOverrides presetHeaders = new ResponseHeaderOverrides();
presetHeaders.setContentDisposition("attachment;filename*=UTF-8''" + encodedFilename);
presetHeaders.setContentType("application/octet-stream");
presetHeaders.setCacheControl("no-cache, no-store, must-revalidate");
req.setResponseHeaders(presetHeaders);
// 6. 生成并返回下载 URL
return amazonS3.generatePresignedUrl(req).toString();
} catch (IllegalArgumentException e) {
// 入参错误直接抛出,上层快速处理
throw e;
} catch (Exception e) {
// 捕获 S3 签名/网络/权限异常,包装后抛出(便于排查)
throw new RuntimeException("生成 S3 强制下载 URL 失败!objectName=" + objectName, e);
}
}
/**
* 获取预览地址
* @param path
@@ -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 以支持进度回调和流式传输