@@ -27,7 +27,9 @@
|
|||||||
"Bash(git checkout:*)",
|
"Bash(git checkout:*)",
|
||||||
"Bash(git diff:*)",
|
"Bash(git diff:*)",
|
||||||
"Bash(grep:*)",
|
"Bash(grep:*)",
|
||||||
"Bash(npm run tsc:*)"
|
"Bash(npm run tsc:*)",
|
||||||
|
"Bash(node:*)",
|
||||||
|
"Bash(javac:*)"
|
||||||
],
|
],
|
||||||
"deny": [],
|
"deny": [],
|
||||||
"ask": []
|
"ask": []
|
||||||
|
|||||||
+172
-66
@@ -22,6 +22,10 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
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 javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
@@ -583,54 +587,95 @@ public class OrderFileController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 代理下载单个文件 - 解决前端跨域问题
|
* 代理下载单个文件 - 真正的流式传输(改进版:零内存积累)
|
||||||
|
*
|
||||||
|
* 优化点:
|
||||||
|
* 1. 使用 StreamingResponseBody,不缓存整个文件在内存
|
||||||
|
* 2. 流式传输,边读边写,避免大文件OOM
|
||||||
|
* 3. 支持超大文件(无GB限制)
|
||||||
|
* 4. 及时flush,让浏览器尽快显示下载
|
||||||
|
* 5. 增大缓冲区到8192字节,提升传输效率
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "下载单个文件")
|
@Operation(summary = "下载单个文件")
|
||||||
@PostMapping("/download")
|
@PostMapping("/download")
|
||||||
public byte[] downloadFile(@RequestBody FileDownloadRequest request) throws IOException {
|
public ResponseEntity<StreamingResponseBody> downloadFile(@RequestBody FileDownloadRequest request) throws IOException {
|
||||||
String fileUrl = request.getUrl();
|
String fileUrl = request.getUrl();
|
||||||
log.info("开始代理下载文件: {}", fileUrl);
|
log.info("📥 开始代理下载文件: {}", fileUrl);
|
||||||
|
|
||||||
if (fileUrl == null || fileUrl.trim().isEmpty()) {
|
if (fileUrl == null || fileUrl.trim().isEmpty()) {
|
||||||
throw new IllegalArgumentException("文件URL不能为空");
|
throw new IllegalArgumentException("文件URL不能为空");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
// 从外部 CDN 下载文件
|
||||||
// 从外部 CDN 下载文件
|
URL url = new URL(fileUrl);
|
||||||
URL url = new URL(fileUrl);
|
URLConnection connection = url.openConnection();
|
||||||
URLConnection connection = url.openConnection();
|
|
||||||
|
|
||||||
// 设置超时
|
// 设置超时和默认User-Agent
|
||||||
connection.setConnectTimeout(10000);
|
connection.setConnectTimeout(10000); // 10秒连接超时
|
||||||
connection.setReadTimeout(30000);
|
connection.setReadTimeout(300000); // 5分钟读取超时,避免网络差时频繁超时
|
||||||
|
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
|
||||||
|
|
||||||
// 获取文件内容
|
// 获取文件大小
|
||||||
byte[] buffer = new byte[4096];
|
long fileSize = connection.getContentLengthLong();
|
||||||
int bytesRead;
|
String fileName = extractFileNameFromUrl(fileUrl);
|
||||||
java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
|
|
||||||
|
|
||||||
try (InputStream input = connection.getInputStream()) {
|
log.info("📊 文件信息: 名称={}, 大小={}MB", fileName, fileSize / (1024 * 1024));
|
||||||
while ((bytesRead = input.read(buffer)) != -1) {
|
|
||||||
byteArrayOutputStream.write(buffer, 0, bytesRead);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
log.info("文件下载成功: {}", extractFileNameFromUrl(fileUrl));
|
// 构建响应头
|
||||||
return byteArrayOutputStream.toByteArray();
|
HttpHeaders headers = new HttpHeaders();
|
||||||
} catch (Exception e) {
|
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
|
||||||
log.error("文件下载失败: fileUrl={}", fileUrl, e);
|
if (fileSize > 0) {
|
||||||
throw new RuntimeException("文件下载失败: " + e.getMessage(), e);
|
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 = "批量下载订单所有资源文件")
|
@Operation(summary = "批量下载订单所有资源文件")
|
||||||
@PostMapping("/download/batch")
|
@PostMapping("/download/batch")
|
||||||
public byte[] batchDownloadFiles(@RequestBody FileDownloadRequest request) {
|
public ResponseEntity<StreamingResponseBody> batchDownloadFiles(@RequestBody FileDownloadRequest request) throws IOException {
|
||||||
String orderNo = request.getOrderNo();
|
String orderNo = request.getOrderNo();
|
||||||
log.info("开始批量下载订单文件: {}", orderNo);
|
log.info("📦 开始批量下载订单文件: {}", orderNo);
|
||||||
|
|
||||||
if (orderNo == null || orderNo.trim().isEmpty()) {
|
if (orderNo == null || orderNo.trim().isEmpty()) {
|
||||||
throw new IllegalArgumentException("订单编号不能为空");
|
throw new IllegalArgumentException("订单编号不能为空");
|
||||||
@@ -640,53 +685,114 @@ public class OrderFileController {
|
|||||||
// 查询订单所有文件
|
// 查询订单所有文件
|
||||||
List<OrderFile> orderFiles = orderFileService.getOrderFileByOrderNo(orderNo);
|
List<OrderFile> orderFiles = orderFileService.getOrderFileByOrderNo(orderNo);
|
||||||
if (CollectionUtils.isEmpty(orderFiles)) {
|
if (CollectionUtils.isEmpty(orderFiles)) {
|
||||||
throw new IllegalArgumentException("订单暂无资源文件");
|
throw new RuntimeException("订单无文件");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建 ZIP 字节流
|
log.info("📊 订单文件数量: {}", orderFiles.size());
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
// ===== 关键优化:使用流式传输,不需要预先计算总大小 =====
|
||||||
// 下载单个文件
|
// 直接处理所有文件,无GB限制(流式传输不需要在内存中积累)
|
||||||
URL fileUrl = new URL(viewUrl);
|
log.info("📊 批量下载文件数: {}", orderFiles.size());
|
||||||
URLConnection connection = fileUrl.openConnection();
|
|
||||||
connection.setConnectTimeout(10000);
|
|
||||||
connection.setReadTimeout(30000);
|
|
||||||
|
|
||||||
String fileName = extractFileNameFromUrl(viewUrl);
|
// 过滤掉无效URL的文件
|
||||||
|
List<OrderFile> filesToDownload = new ArrayList<>();
|
||||||
// 创建 ZIP 条目
|
for (OrderFile file : orderFiles) {
|
||||||
ZipEntry zipEntry = new ZipEntry(fileName);
|
String viewUrl = fileCenterService.getFileViewUrl(file.getFileId());
|
||||||
zipOut.putNextEntry(zipEntry);
|
if (viewUrl != null && !viewUrl.isEmpty()) {
|
||||||
|
filesToDownload.add(file);
|
||||||
// 写入文件内容到 ZIP
|
} else {
|
||||||
try (InputStream fileInput = connection.getInputStream()) {
|
log.warn("文件URL为空,跳过: {}", file.getFileId());
|
||||||
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);
|
|
||||||
// 继续处理其他文件
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info("批量下载完成: {}", orderNo);
|
if (filesToDownload.isEmpty()) {
|
||||||
return byteArrayOutputStream.toByteArray();
|
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) {
|
} catch (Exception e) {
|
||||||
log.error("批量下载文件失败: orderNo={}", orderNo, e);
|
log.error("❌ 批量下载文件失败: orderNo={}", orderNo, e);
|
||||||
throw new RuntimeException("批量下载失败: " + e.getMessage(), e);
|
throw new RuntimeException("批量下载失败: " + e.getMessage(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,12 @@ interface OrderResourcesModalProps {
|
|||||||
onCancel: () => void;
|
onCancel: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface DownloadProgress {
|
||||||
|
fileId: string | number;
|
||||||
|
progress: number; // 0-100
|
||||||
|
isLoading: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
// 判断文件类型(通过 MIME type 或文件扩展名)
|
// 判断文件类型(通过 MIME type 或文件扩展名)
|
||||||
const isImageFile = (file: OrderFile): boolean => {
|
const isImageFile = (file: OrderFile): boolean => {
|
||||||
const fileType = file.fileType?.toLowerCase() || '';
|
const fileType = file.fileType?.toLowerCase() || '';
|
||||||
@@ -61,6 +67,7 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
|
const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [batchDownloading, setBatchDownloading] = useState(false);
|
const [batchDownloading, setBatchDownloading] = useState(false);
|
||||||
|
const [downloadingFiles, setDownloadingFiles] = useState<Map<string | number, DownloadProgress>>(new Map());
|
||||||
|
|
||||||
// 当弹窗打开时加载资源列表
|
// 当弹窗打开时加载资源列表
|
||||||
const loadResources = useCallback(async () => {
|
const loadResources = useCallback(async () => {
|
||||||
@@ -99,17 +106,51 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
const images = resources.filter(isImageFile);
|
const images = resources.filter(isImageFile);
|
||||||
const videos = resources.filter(isVideoFile);
|
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) => {
|
const handleDownload = async (url: string, fileName?: string) => {
|
||||||
if (!url) return;
|
if (!url) return;
|
||||||
|
|
||||||
|
const fileId = getFileId(url, fileName);
|
||||||
const finalFileName = fileName || `file_${Date.now()}`;
|
const finalFileName = fileName || `file_${Date.now()}`;
|
||||||
console.log(`⬇️ Starting download: ${url} as ${finalFileName}`);
|
console.log(`⬇️ Starting download: ${url} as ${finalFileName}`);
|
||||||
|
|
||||||
|
// 禁用按钮,显示进度
|
||||||
|
updateDownloadProgress(fileId, 0, true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 方式1: 通过后端代理下载(推荐 - 解决跨域问题)
|
// 方式1: 通过后端代理下载(推荐 - 解决跨域问题,支持进度回调)
|
||||||
console.log('📌 Downloading via backend proxy...');
|
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 blobUrl = window.URL.createObjectURL(blob as Blob);
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
@@ -118,14 +159,19 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
a.style.display = 'none';
|
a.style.display = 'none';
|
||||||
document.body.appendChild(a);
|
document.body.appendChild(a);
|
||||||
|
|
||||||
|
updateDownloadProgress(fileId, 90, true);
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
a.click();
|
a.click();
|
||||||
console.log(`✅ Download started via backend proxy: ${finalFileName}`);
|
console.log(`✅ Download started via backend proxy: ${finalFileName}`);
|
||||||
|
updateDownloadProgress(fileId, 100, false);
|
||||||
|
|
||||||
|
// 延迟500ms后隐藏进度条,让用户看到完成状态
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
|
removeDownloadProgress(fileId);
|
||||||
document.body.removeChild(a);
|
document.body.removeChild(a);
|
||||||
window.URL.revokeObjectURL(blobUrl);
|
window.URL.revokeObjectURL(blobUrl);
|
||||||
}, 100);
|
}, 500);
|
||||||
}, 0);
|
}, 0);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
@@ -135,14 +181,27 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
try {
|
try {
|
||||||
// 方式2: 尝试 XMLHttpRequest(本地可用但跨域受限)
|
// 方式2: 尝试 XMLHttpRequest(本地可用但跨域受限)
|
||||||
console.log('📌 Trying XHR method...');
|
console.log('📌 Trying XHR method...');
|
||||||
|
updateDownloadProgress(fileId, 30, true);
|
||||||
|
|
||||||
return await new Promise((resolve, reject) => {
|
return await new Promise((resolve, reject) => {
|
||||||
const xhr = new XMLHttpRequest();
|
const xhr = new XMLHttpRequest();
|
||||||
xhr.open('GET', url, true);
|
xhr.open('GET', url, true);
|
||||||
xhr.responseType = 'blob';
|
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 = () => {
|
xhr.onload = () => {
|
||||||
if (xhr.status === 200) {
|
if (xhr.status === 200) {
|
||||||
const blob = xhr.response;
|
const blob = xhr.response;
|
||||||
|
updateDownloadProgress(fileId, 90, true);
|
||||||
|
|
||||||
const blobUrl = window.URL.createObjectURL(blob);
|
const blobUrl = window.URL.createObjectURL(blob);
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.href = blobUrl;
|
a.href = blobUrl;
|
||||||
@@ -153,12 +212,14 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
a.click();
|
a.click();
|
||||||
console.log(`✅ Download started via XHR: ${finalFileName}`);
|
console.log(`✅ Download started via XHR: ${finalFileName}`);
|
||||||
|
updateDownloadProgress(fileId, 100, false);
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
|
removeDownloadProgress(fileId);
|
||||||
document.body.removeChild(a);
|
document.body.removeChild(a);
|
||||||
window.URL.revokeObjectURL(blobUrl);
|
window.URL.revokeObjectURL(blobUrl);
|
||||||
resolve(true);
|
resolve(true);
|
||||||
}, 100);
|
}, 500);
|
||||||
}, 0);
|
}, 0);
|
||||||
} else {
|
} else {
|
||||||
reject(new Error(`HTTP ${xhr.status}`));
|
reject(new Error(`HTTP ${xhr.status}`));
|
||||||
@@ -174,6 +235,7 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
});
|
});
|
||||||
} catch (xhrError) {
|
} catch (xhrError) {
|
||||||
console.error(`❌ XHR方式失败:`, xhrError);
|
console.error(`❌ XHR方式失败:`, xhrError);
|
||||||
|
removeDownloadProgress(fileId);
|
||||||
|
|
||||||
// 方式3: 降级到直接链接 + 新窗口
|
// 方式3: 降级到直接链接 + 新窗口
|
||||||
console.log('📌 Falling back to direct link in new window...');
|
console.log('📌 Falling back to direct link in new window...');
|
||||||
@@ -188,7 +250,7 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 批量下载所有文件 - 并发调用单个文件下载接口
|
// 批量下载所有文件 - 调用后端批量下载接口(推荐)
|
||||||
const handleBatchDownload = async () => {
|
const handleBatchDownload = async () => {
|
||||||
if (!record?.orderNo) {
|
if (!record?.orderNo) {
|
||||||
console.warn('⚠️ orderNo is missing');
|
console.warn('⚠️ orderNo is missing');
|
||||||
@@ -196,65 +258,104 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
}
|
}
|
||||||
|
|
||||||
const orderNo = record.orderNo;
|
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}`);
|
console.log(`📊 Total files to download: ${resources.length}`);
|
||||||
setBatchDownloading(true);
|
setBatchDownloading(true);
|
||||||
|
|
||||||
|
const startTime = Date.now();
|
||||||
|
let lastUpdateTime = startTime;
|
||||||
|
let lastDownloadedBytes = 0;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 并发下载所有文件 - 让浏览器自动管理并发
|
// 创建虚拟进度条项
|
||||||
const downloadPromises = resources.map(async (file, index) => {
|
updateDownloadProgress('batch_all', 0, true);
|
||||||
if (!file.viewUrl) {
|
|
||||||
console.warn(`⚠️ Skipping file without URL: ${file.filePath}`);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const fileName = file.filePath ? file.filePath.split('/').pop() : `file_${index + 1}`;
|
// 调用后端批量下载接口,一次性生成ZIP
|
||||||
console.log(`📥 Queuing download (${index + 1}/${resources.length}): ${fileName}`);
|
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 {
|
// 计算下载的大小(MB)
|
||||||
// 调用单个文件下载接口获取 blob
|
const downloadedMB = (downloadedBytes / (1024 * 1024)).toFixed(2);
|
||||||
const blob = await ordersApi.downloadFile(file.viewUrl);
|
|
||||||
|
|
||||||
// 创建下载链接并触发浏览器下载
|
// 存储已下载信息用于显示(使用一个特殊属性)
|
||||||
const blobUrl = window.URL.createObjectURL(blob as Blob);
|
const progressObj = {
|
||||||
const a = document.createElement('a');
|
fileId: 'batch_all',
|
||||||
a.href = blobUrl;
|
downloadedBytes,
|
||||||
if (fileName != null) {
|
downloadedMB,
|
||||||
a.download = fileName;
|
speed: speed.toFixed(2),
|
||||||
}else {
|
elapsedSeconds: elapsedSeconds.toFixed(1),
|
||||||
a.download = '文件下载';
|
progress: Math.min(90, (downloadedBytes / (1024 * 1024 * 100)) * 100),
|
||||||
}
|
isLoading: true
|
||||||
a.style.display = 'none';
|
};
|
||||||
document.body.appendChild(a);
|
|
||||||
// 添加延迟以错开下载请求,避免浏览器并发限制
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, index * 150));
|
|
||||||
a.click();
|
|
||||||
console.log(`✅ Download triggered: ${fileName}`);
|
|
||||||
|
|
||||||
// 清理资源
|
setDownloadingFiles(prev => {
|
||||||
setTimeout(() => {
|
const newMap = new Map(prev);
|
||||||
document.body.removeChild(a);
|
newMap.set('batch_all', progressObj as any);
|
||||||
window.URL.revokeObjectURL(blobUrl);
|
return newMap;
|
||||||
}, 500);
|
});
|
||||||
|
console.log(`📊 已下载: ${downloadedMB}MB, 速度: ${speed.toFixed(2)}MB/s, 耗时: ${elapsedSeconds.toFixed(1)}s`);
|
||||||
return true;
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`❌ Failed to download: ${fileName}`, error);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// 等待所有下载请求完成(不等待浏览器下载完成)
|
// 检查是否成功
|
||||||
const results = await Promise.all(downloadPromises);
|
if (!blob || blob.size === 0) {
|
||||||
const successCount = results.filter((r) => r).length;
|
throw new Error('下载的文件为空');
|
||||||
const failureCount = results.filter((r) => !r).length;
|
}
|
||||||
|
|
||||||
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}`);
|
console.log(`🎉 ${message}`);
|
||||||
alert(message);
|
alert(message);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`❌ Batch download failed:`, 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 {
|
} finally {
|
||||||
setBatchDownloading(false);
|
setBatchDownloading(false);
|
||||||
}
|
}
|
||||||
@@ -276,6 +377,10 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
) : (
|
) : (
|
||||||
images.map((item, idx) => {
|
images.map((item, idx) => {
|
||||||
const fileName = getFileName(item, idx);
|
const fileName = getFileName(item, idx);
|
||||||
|
const fileId = getFileId(item.viewUrl, fileName);
|
||||||
|
const downloadState = downloadingFiles.get(fileId);
|
||||||
|
const isDownloading = !!downloadState && downloadState.isLoading;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Tooltip key={item.id || idx} title={fileName}>
|
<Tooltip key={item.id || idx} title={fileName}>
|
||||||
<div
|
<div
|
||||||
@@ -313,13 +418,41 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
}}>
|
}}>
|
||||||
{fileName}
|
{fileName}
|
||||||
</div>
|
</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
|
<Button
|
||||||
type="primary"
|
type="primary"
|
||||||
size="small"
|
size="small"
|
||||||
icon={<DownloadOutlined />}
|
icon={<DownloadOutlined />}
|
||||||
|
loading={isDownloading}
|
||||||
|
disabled={isDownloading}
|
||||||
|
title={isDownloading ? `下载中... ${downloadState?.progress || 0}%` : '下载'}
|
||||||
onClick={async (e) => {
|
onClick={async (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
if (item.viewUrl) {
|
if (item.viewUrl && !isDownloading) {
|
||||||
await handleDownload(item.viewUrl, fileName);
|
await handleDownload(item.viewUrl, fileName);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
@@ -327,7 +460,7 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
top: '4px',
|
top: '4px',
|
||||||
right: '4px',
|
right: '4px',
|
||||||
opacity: 0.8
|
opacity: isDownloading ? 0.6 : 0.8
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -347,6 +480,10 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
<div style={{ display: 'grid', gap: '16px' }}>
|
<div style={{ display: 'grid', gap: '16px' }}>
|
||||||
{videos.map((item, idx) => {
|
{videos.map((item, idx) => {
|
||||||
const fileName = getFileName(item, idx);
|
const fileName = getFileName(item, idx);
|
||||||
|
const fileId = getFileId(item.viewUrl, fileName);
|
||||||
|
const downloadState = downloadingFiles.get(fileId);
|
||||||
|
const isDownloading = !!downloadState && downloadState.isLoading;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={item.id || idx}
|
key={item.id || idx}
|
||||||
@@ -364,8 +501,9 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
display: 'flex',
|
display: 'flex',
|
||||||
justifyContent: 'space-between',
|
justifyContent: 'space-between',
|
||||||
alignItems: 'center',
|
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' }} />
|
<PlayCircleOutlined style={{ fontSize: '18px', color: '#1890ff' }} />
|
||||||
<span style={{ fontWeight: 500, maxWidth: '400px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
<span style={{ fontWeight: 500, maxWidth: '400px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||||
{fileName}
|
{fileName}
|
||||||
@@ -375,16 +513,42 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
type="primary"
|
type="primary"
|
||||||
size="small"
|
size="small"
|
||||||
icon={<DownloadOutlined />}
|
icon={<DownloadOutlined />}
|
||||||
|
loading={isDownloading}
|
||||||
|
disabled={isDownloading}
|
||||||
|
title={isDownloading ? `下载中... ${downloadState?.progress || 0}%` : '下载'}
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (item.viewUrl) {
|
if (item.viewUrl && !isDownloading) {
|
||||||
await handleDownload(item.viewUrl, fileName);
|
await handleDownload(item.viewUrl, fileName);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
|
style={{ marginLeft: '8px' }}
|
||||||
>
|
>
|
||||||
下载
|
{isDownloading ? `下载中 ${downloadState?.progress || 0}%` : '下载'}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</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={{
|
<div style={{
|
||||||
marginBottom: '12px',
|
marginBottom: '12px',
|
||||||
@@ -432,6 +596,17 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
</div>
|
</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 变化时加载资源
|
// 使用 effect 在 visible 变化时加载资源
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (visible) {
|
if (visible) {
|
||||||
@@ -458,10 +633,19 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
type="primary"
|
type="primary"
|
||||||
icon={<DownloadOutlined />}
|
icon={<DownloadOutlined />}
|
||||||
loading={batchDownloading}
|
loading={batchDownloading}
|
||||||
disabled={resources.length === 0 || loading}
|
disabled={resources.length === 0 || loading || batchDownloading}
|
||||||
onClick={handleBatchDownload}
|
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>,
|
</Button>,
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -322,14 +322,55 @@ export const ordersApi = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
// 下载文件 - 通过后端代理(解决跨域问题)
|
// 下载文件 - 通过后端代理(解决跨域问题)
|
||||||
downloadFile: async (fileUrl: string) => {
|
// 优化:改为流式传输,支持大文件下载、断点续传
|
||||||
|
// 注意:使用 XMLHttpRequest 以支持进度回调和流式传输
|
||||||
|
downloadFile: async (fileUrl: string, onProgress?: (progress: number) => void) => {
|
||||||
try {
|
try {
|
||||||
const res = await request('/api-order/files/download', {
|
// 获取当前token,用于请求头
|
||||||
method: 'POST',
|
const token = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('access_token') : null;
|
||||||
data: { url: fileUrl },
|
|
||||||
responseType: 'blob',
|
return await new Promise<Blob>((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) {
|
} catch (error) {
|
||||||
console.error('❌ downloadFile error:', error);
|
console.error('❌ downloadFile error:', error);
|
||||||
throw error;
|
throw error;
|
||||||
@@ -337,14 +378,62 @@ export const ordersApi = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
// 批量下载所有文件 - 打包为 ZIP
|
// 批量下载所有文件 - 打包为 ZIP
|
||||||
batchDownloadFiles: async (orderNo: string) => {
|
// 优化:改为流式传输,支持大型ZIP下载
|
||||||
|
batchDownloadFiles: async (orderNo: string, onProgress?: (progress: number) => void) => {
|
||||||
try {
|
try {
|
||||||
const res = await request('/api-order/files/download/batch', {
|
// 获取当前token,用于请求头
|
||||||
method: 'POST',
|
const token = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('access_token') : null;
|
||||||
data: { orderNo },
|
|
||||||
responseType: 'blob',
|
return await new Promise<Blob>((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) {
|
} catch (error) {
|
||||||
console.error('❌ batchDownloadFiles error:', error);
|
console.error('❌ batchDownloadFiles error:', error);
|
||||||
throw error;
|
throw error;
|
||||||
|
|||||||
Reference in New Issue
Block a user