Merge pull request !62 from 鸭先知/test
This commit is contained in:
@@ -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": []
|
||||||
|
|||||||
@@ -120,6 +120,11 @@ public class FileController {
|
|||||||
return timeWindowStorageService.getSmartViewUrl(id);
|
return timeWindowStorageService.getSmartViewUrl(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GetMapping("/file/download/{id}")
|
||||||
|
public String getFiledownloadUrl(@PathVariable String id) {
|
||||||
|
return timeWindowStorageService.getFileDownLoadUrl(id);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据文件ID获取智能访问 URL(Result 包装)
|
* 根据文件ID获取智能访问 URL(Result 包装)
|
||||||
*/
|
*/
|
||||||
|
|||||||
+90
@@ -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)
|
* 智能获取文件访问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
|
* 根据存储类型获取访问URL
|
||||||
*/
|
*/
|
||||||
@@ -295,6 +339,25 @@ public class TimeWindowStorageService {
|
|||||||
return "";
|
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
|
* 从S3查询文件URL
|
||||||
*/
|
*/
|
||||||
@@ -361,6 +424,33 @@ public class TimeWindowStorageService {
|
|||||||
return "";
|
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(通过路径)
|
* 从S3查询文件URL(通过路径)
|
||||||
*/
|
*/
|
||||||
|
|||||||
+2
@@ -111,6 +111,8 @@ public abstract class AbstractIFileService extends ServiceImpl<FileMapper, FileI
|
|||||||
|
|
||||||
public abstract String getViewUrlByPath(String name);
|
public abstract String getViewUrlByPath(String name);
|
||||||
|
|
||||||
|
public abstract String getDownloadUrl(String path);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public FileInfo getFileInfo(String id) {
|
public FileInfo getFileInfo(String id) {
|
||||||
return baseMapper.selectById(id);
|
return baseMapper.selectById(id);
|
||||||
|
|||||||
@@ -55,6 +55,11 @@ public class CosService extends AbstractIFileService {
|
|||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getDownloadUrl(String path) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getZipViewUrlByPath(String name, String style) {
|
public String getZipViewUrlByPath(String name, String style) {
|
||||||
return "";
|
return "";
|
||||||
|
|||||||
+5
@@ -89,6 +89,11 @@ public class EnhancedS3Service extends AbstractIFileService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getDownloadUrl(String path) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getZipViewUrlByPath(String name, String style) {
|
public String getZipViewUrlByPath(String name, String style) {
|
||||||
// 实现压缩文件URL获取逻辑
|
// 实现压缩文件URL获取逻辑
|
||||||
|
|||||||
+5
@@ -51,6 +51,11 @@ public class FastdfsService extends AbstractIFileService {
|
|||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getDownloadUrl(String path) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getZipViewUrlByPath(String name, String style) {
|
public String getZipViewUrlByPath(String name, String style) {
|
||||||
return "";
|
return "";
|
||||||
|
|||||||
@@ -86,6 +86,11 @@ public class OssService extends AbstractIFileService {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getDownloadUrl(String path) {
|
||||||
|
return ossTemplate.getDownloadUrl(path);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getZipViewUrlByPath(String path, String style) {
|
public String getZipViewUrlByPath(String path, String style) {
|
||||||
return ossTemplate.getViewUrl(path,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
|
@Override
|
||||||
public String getZipViewUrlByPath(String name, String style) {
|
public String getZipViewUrlByPath(String name, String style) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
+183
-77
@@ -22,12 +22,12 @@ 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 javax.servlet.http.HttpServletResponse;
|
import org.springframework.http.HttpHeaders;
|
||||||
import java.io.ByteArrayOutputStream;
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.OutputStream;
|
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.net.URLConnection;
|
import java.net.URLConnection;
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
@@ -583,110 +583,204 @@ 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不能为空");
|
||||||
}
|
}
|
||||||
|
// 从外部 CDN 下载文件
|
||||||
try {
|
URL url = new URL(fileUrl);
|
||||||
// 从外部 CDN 下载文件
|
URLConnection connection = url.openConnection();
|
||||||
URL url = new URL(fileUrl);
|
// 设置超时和默认User-Agent
|
||||||
URLConnection connection = url.openConnection();
|
connection.setConnectTimeout(10000); // 10秒连接超时
|
||||||
|
connection.setReadTimeout(300000); // 5分钟读取超时,避免网络差时频繁超时
|
||||||
// 设置超时
|
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
|
||||||
connection.setConnectTimeout(10000);
|
// 获取文件大小
|
||||||
connection.setReadTimeout(30000);
|
long fileSize = connection.getContentLengthLong();
|
||||||
|
String fileName = extractFileNameFromUrl(fileUrl);
|
||||||
// 获取文件内容
|
log.info("📊 文件信息: 名称={}, 大小={}MB", fileName, fileSize / (1024 * 1024));
|
||||||
byte[] buffer = new byte[4096];
|
// 构建响应头
|
||||||
int bytesRead;
|
HttpHeaders headers = new HttpHeaders();
|
||||||
java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
|
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
|
||||||
|
if (fileSize > 0) {
|
||||||
try (InputStream input = connection.getInputStream()) {
|
headers.setContentLength(fileSize);
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
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("订单编号不能为空");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 查询订单所有文件
|
// 查询订单所有文件
|
||||||
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,4 +70,8 @@ public interface FileCenterService {
|
|||||||
Result<Boolean> batchPrefetchFiles(@RequestBody List<String> urls,
|
Result<Boolean> batchPrefetchFiles(@RequestBody List<String> urls,
|
||||||
@RequestParam(value = "batchSize", defaultValue = "100") int batchSize,
|
@RequestParam(value = "batchSize", defaultValue = "100") int batchSize,
|
||||||
@RequestParam(value = "area", required = false) String area);
|
@RequestParam(value = "area", required = false) String area);
|
||||||
|
|
||||||
|
|
||||||
|
@GetMapping("/file/download/{id}")
|
||||||
|
String getFileDownLoadUrl(@PathVariable("id") String id);
|
||||||
}
|
}
|
||||||
|
|||||||
+5
@@ -73,6 +73,11 @@ public class FileCenterServiceFallbackFactory implements FallbackFactory<FileCen
|
|||||||
return Result.failed("CDN批量预热文件失败: " + cause.getMessage());
|
return Result.failed("CDN批量预热文件失败: " + cause.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getFileDownLoadUrl(String id) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+64
-3
@@ -11,14 +11,18 @@ import org.springframework.beans.factory.InitializingBean;
|
|||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.util.ArrayList;
|
import java.net.URLEncoder;
|
||||||
import java.util.Calendar;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.List;
|
import java.nio.file.Paths;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* cos 配置
|
* cos 配置
|
||||||
@@ -168,6 +172,63 @@ public class OssTemplate implements InitializingBean {
|
|||||||
return url.toString();
|
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) {
|
public void out(String objectName, OutputStream os) {
|
||||||
out(fileProperties.getOss().getBucketName(), objectName, os);
|
out(fileProperties.getOss().getBucketName(), objectName, os);
|
||||||
}
|
}
|
||||||
|
|||||||
+64
-4
@@ -1,6 +1,7 @@
|
|||||||
package com.central.oss.template;
|
package com.central.oss.template;
|
||||||
|
|
||||||
import com.amazonaws.ClientConfiguration;
|
import com.amazonaws.ClientConfiguration;
|
||||||
|
import com.amazonaws.HttpMethod;
|
||||||
import com.amazonaws.auth.AWSCredentials;
|
import com.amazonaws.auth.AWSCredentials;
|
||||||
import com.amazonaws.auth.AWSCredentialsProvider;
|
import com.amazonaws.auth.AWSCredentialsProvider;
|
||||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||||
@@ -8,10 +9,7 @@ import com.amazonaws.auth.BasicAWSCredentials;
|
|||||||
import com.amazonaws.client.builder.AwsClientBuilder;
|
import com.amazonaws.client.builder.AwsClientBuilder;
|
||||||
import com.amazonaws.services.s3.AmazonS3;
|
import com.amazonaws.services.s3.AmazonS3;
|
||||||
import com.amazonaws.services.s3.AmazonS3Client;
|
import com.amazonaws.services.s3.AmazonS3Client;
|
||||||
import com.amazonaws.services.s3.model.ObjectMetadata;
|
import com.amazonaws.services.s3.model.*;
|
||||||
import com.amazonaws.services.s3.model.PutObjectRequest;
|
|
||||||
import com.amazonaws.services.s3.model.S3Object;
|
|
||||||
import com.amazonaws.services.s3.model.S3ObjectInputStream;
|
|
||||||
import com.amazonaws.util.IOUtils;
|
import com.amazonaws.util.IOUtils;
|
||||||
import com.central.oss.model.ObjectInfo;
|
import com.central.oss.model.ObjectInfo;
|
||||||
import com.central.oss.properties.FileServerProperties;
|
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.ConditionalOnClass;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
import javax.annotation.Resource;
|
import javax.annotation.Resource;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.net.URL;
|
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.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* aws s3配置
|
* aws s3配置
|
||||||
@@ -125,6 +130,61 @@ public class S3Template implements InitializingBean {
|
|||||||
return url.toString();
|
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");
|
||||||
|
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);
|
||||||
|
}*/
|
||||||
|
String url = getViewUrlNoExpires(objectName);
|
||||||
|
return url+"?"+"response-content-disposition=attachment";
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取预览地址
|
* 获取预览地址
|
||||||
* @param path
|
* @param path
|
||||||
|
|||||||
@@ -24,6 +24,7 @@
|
|||||||
"antd": "^4.20.0",
|
"antd": "^4.20.0",
|
||||||
"file-saver": "^2.0.5",
|
"file-saver": "^2.0.5",
|
||||||
"jsencrypt": "^3.5.4",
|
"jsencrypt": "^3.5.4",
|
||||||
|
"jszip": "^3.10.1",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
"moment": "^2.29.0",
|
"moment": "^2.29.0",
|
||||||
"react": "^17.0.2",
|
"react": "^17.0.2",
|
||||||
|
|||||||
+329
-147
@@ -1,9 +1,11 @@
|
|||||||
import React, { useState, useCallback } from 'react';
|
import React, { useState, useCallback } from 'react';
|
||||||
import { Modal, Spin, Empty, Image, Badge, Tabs, Space, Button, Tooltip } from 'antd';
|
import { Modal, Spin, Empty, Image, Badge, Tabs, Space, Button, Tooltip, message, Popconfirm } from 'antd';
|
||||||
import { DownloadOutlined, PictureOutlined, PlayCircleOutlined } from '@ant-design/icons';
|
import { DownloadOutlined, PictureOutlined, PlayCircleOutlined, FileZipOutlined, DeleteOutlined } from '@ant-design/icons';
|
||||||
import { ordersApi } from '@/services/orders';
|
import { ordersApi } from '@/services/orders';
|
||||||
import type { OrderItem } from '@/services/orders';
|
import type { OrderItem } from '@/services/orders';
|
||||||
import {dateFormatterMap} from "@ant-design/pro-components";
|
import {dateFormatterMap} from "@ant-design/pro-components";
|
||||||
|
import JSZip from 'jszip';
|
||||||
|
import { saveAs } from 'file-saver';
|
||||||
|
|
||||||
interface OrderFile {
|
interface OrderFile {
|
||||||
id?: number | string;
|
id?: number | string;
|
||||||
@@ -24,6 +26,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 +69,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 () => {
|
||||||
@@ -82,7 +91,6 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await ordersApi.getOrderResources(orderNo);
|
const data = await ordersApi.getOrderResources(orderNo);
|
||||||
console.log(`📊 Got ${data?.length || 0} resources:`, data);
|
|
||||||
setResources(Array.isArray(data) ? data : []);
|
setResources(Array.isArray(data) ? data : []);
|
||||||
setHasLoadedOnce(true);
|
setHasLoadedOnce(true);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@@ -99,162 +107,201 @@ 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 handleDownload = async (url: string, fileName?: string) => {
|
const getFileId = (url: string | undefined, fileName?: string): string => {
|
||||||
if (!url) return;
|
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 {
|
try {
|
||||||
// 方式1: 通过后端代理下载(推荐 - 解决跨域问题)
|
message.loading('正在删除文件...', 0);
|
||||||
console.log('📌 Downloading via backend proxy...');
|
|
||||||
const blob = await ordersApi.downloadFile(url);
|
|
||||||
|
|
||||||
const blobUrl = window.URL.createObjectURL(blob as Blob);
|
// 调用删除接口
|
||||||
const a = document.createElement('a');
|
await ordersApi.deleteOrderFile(Number(fileId));
|
||||||
a.href = blobUrl;
|
|
||||||
a.download = finalFileName;
|
|
||||||
a.style.display = 'none';
|
|
||||||
document.body.appendChild(a);
|
|
||||||
|
|
||||||
setTimeout(() => {
|
message.destroy();
|
||||||
a.click();
|
message.success('删除成功');
|
||||||
console.log(`✅ Download started via backend proxy: ${finalFileName}`);
|
|
||||||
|
|
||||||
setTimeout(() => {
|
// 重新加载资源列表
|
||||||
document.body.removeChild(a);
|
setHasLoadedOnce(false);
|
||||||
window.URL.revokeObjectURL(blobUrl);
|
await loadResources();
|
||||||
}, 100);
|
|
||||||
}, 0);
|
|
||||||
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`❌ Backend proxy download failed:`, error);
|
message.destroy();
|
||||||
|
console.error('删除文件失败:', error);
|
||||||
try {
|
message.error('删除失败,请重试');
|
||||||
// 方式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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 批量下载所有文件 - 并发调用单个文件下载接口
|
// 处理下载 - 获取URL后用 <a> 标签强制下载
|
||||||
|
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);
|
||||||
|
|
||||||
|
// 创建临时 <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(() => {
|
||||||
|
removeDownloadProgress(fileId);
|
||||||
|
}, 300);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
removeDownloadProgress(fileId);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 批量下载所有文件为 ZIP - 前端打包
|
||||||
const handleBatchDownload = async () => {
|
const handleBatchDownload = async () => {
|
||||||
if (!record?.orderNo) {
|
if (!record?.orderNo) {
|
||||||
console.warn('⚠️ orderNo is missing');
|
message.warning('订单号缺失');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const orderNo = record.orderNo;
|
const orderNo = record.orderNo;
|
||||||
console.log(`⬇️ Starting batch download for order: ${orderNo}`);
|
console.log(`📦 开始批量下载并打包为 ZIP: ${orderNo}`);
|
||||||
console.log(`📊 Total files to download: ${resources.length}`);
|
console.log(`📊 总文件数: ${resources.length}`);
|
||||||
setBatchDownloading(true);
|
setBatchDownloading(true);
|
||||||
|
|
||||||
|
const startTime = Date.now();
|
||||||
|
|
||||||
try {
|
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) => {
|
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 {
|
try {
|
||||||
// 调用单个文件下载接口获取 blob
|
if (!file.fileId) {
|
||||||
const blob = await ordersApi.downloadFile(file.viewUrl);
|
failureCount++;
|
||||||
|
return;
|
||||||
// 创建下载链接并触发浏览器下载
|
|
||||||
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 = '文件下载';
|
|
||||||
}
|
}
|
||||||
a.style.display = 'none';
|
|
||||||
document.body.appendChild(a);
|
|
||||||
// 添加延迟以错开下载请求,避免浏览器并发限制
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, index * 150));
|
|
||||||
a.click();
|
|
||||||
console.log(`✅ Download triggered: ${fileName}`);
|
|
||||||
|
|
||||||
// 清理资源
|
// 获取下载 URL
|
||||||
setTimeout(() => {
|
const downloadUrl = await ordersApi.getFileDownloadUrl(file.fileId);
|
||||||
document.body.removeChild(a);
|
if (!downloadUrl) {
|
||||||
window.URL.revokeObjectURL(blobUrl);
|
failureCount++;
|
||||||
}, 500);
|
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) {
|
} catch (error) {
|
||||||
console.error(`❌ Failed to download: ${fileName}`, error);
|
console.error(`❌ 处理文件失败:`, error);
|
||||||
return false;
|
failureCount++;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 等待所有下载请求完成(不等待浏览器下载完成)
|
// 等待所有下载完成
|
||||||
const results = await Promise.all(downloadPromises);
|
await Promise.allSettled(downloadPromises);
|
||||||
const successCount = results.filter((r) => r).length;
|
|
||||||
const failureCount = results.filter((r) => !r).length;
|
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) {
|
} catch (error) {
|
||||||
console.error(`❌ Batch download failed:`, error);
|
console.error(`❌ ZIP 打包失败:`, error);
|
||||||
alert('批量下载失败,请重试');
|
message.error('打包下载失败,请重试');
|
||||||
|
removeDownloadProgress('batch_all');
|
||||||
} finally {
|
} finally {
|
||||||
setBatchDownloading(false);
|
setBatchDownloading(false);
|
||||||
}
|
}
|
||||||
@@ -276,6 +323,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,21 +364,80 @@ 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>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 删除按钮 - 左上角 */}
|
||||||
|
<Popconfirm
|
||||||
|
title="确定删除这个文件吗?"
|
||||||
|
onConfirm={async (e) => {
|
||||||
|
e?.stopPropagation();
|
||||||
|
if (item.id) {
|
||||||
|
await handleDeleteFile(item.id);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
okText="确定"
|
||||||
|
cancelText="取消"
|
||||||
|
placement="bottomRight"
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
danger
|
||||||
|
size="small"
|
||||||
|
icon={<DeleteOutlined />}
|
||||||
|
title="删除"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
top: '4px',
|
||||||
|
left: '4px',
|
||||||
|
zIndex: 10,
|
||||||
|
opacity: 0.9
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Popconfirm>
|
||||||
|
|
||||||
|
{/* 下载按钮 - 右上角 */}
|
||||||
<Button
|
<Button
|
||||||
type="primary"
|
type="primary"
|
||||||
size="small"
|
size="small"
|
||||||
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 && !isDownloading) {
|
||||||
await handleDownload(item.viewUrl, fileName);
|
await handleDownload(item, fileName);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
style={{
|
style={{
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
top: '4px',
|
top: '4px',
|
||||||
right: '4px',
|
right: '4px',
|
||||||
opacity: 0.8
|
opacity: isDownloading ? 0.6 : 0.9
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -347,6 +457,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,26 +478,74 @@ 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}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<Space>
|
||||||
type="primary"
|
<Button
|
||||||
size="small"
|
type="primary"
|
||||||
icon={<DownloadOutlined />}
|
size="small"
|
||||||
onClick={async () => {
|
icon={<DownloadOutlined />}
|
||||||
if (item.viewUrl) {
|
loading={isDownloading}
|
||||||
await handleDownload(item.viewUrl, fileName);
|
disabled={isDownloading}
|
||||||
}
|
title={isDownloading ? `下载中... ${downloadState?.progress || 0}%` : '下载'}
|
||||||
|
onClick={async () => {
|
||||||
|
if (item && !isDownloading) {
|
||||||
|
await handleDownload(item, fileName);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isDownloading ? `下载中 ${downloadState?.progress || 0}%` : '下载'}
|
||||||
|
</Button>
|
||||||
|
<Popconfirm
|
||||||
|
title="确定删除这个视频吗?"
|
||||||
|
onConfirm={async () => {
|
||||||
|
if (item.id) {
|
||||||
|
await handleDeleteFile(item.id);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
okText="确定"
|
||||||
|
cancelText="取消"
|
||||||
|
placement="bottomLeft"
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
danger
|
||||||
|
icon={<DeleteOutlined />}
|
||||||
|
title="删除视频"
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 下载进度条 */}
|
||||||
|
{downloadState && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
marginBottom: '12px',
|
||||||
|
height: '4px',
|
||||||
|
backgroundColor: 'rgba(0,0,0,0.1)',
|
||||||
|
borderRadius: '2px',
|
||||||
|
overflow: 'hidden'
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
下载
|
<div
|
||||||
</Button>
|
style={{
|
||||||
</div>
|
height: '100%',
|
||||||
|
backgroundColor: '#1890ff',
|
||||||
|
width: `${downloadState.progress}%`,
|
||||||
|
transition: 'width 0.3s ease'
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* 视频播放器 */}
|
{/* 视频播放器 */}
|
||||||
<div style={{
|
<div style={{
|
||||||
@@ -432,6 +594,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) {
|
||||||
@@ -456,12 +629,21 @@ const OrderResourcesModal: React.FC<OrderResourcesModalProps> = ({ visible, reco
|
|||||||
<Button
|
<Button
|
||||||
key="batch-download"
|
key="batch-download"
|
||||||
type="primary"
|
type="primary"
|
||||||
icon={<DownloadOutlined />}
|
icon={<FileZipOutlined />}
|
||||||
loading={batchDownloading}
|
loading={batchDownloading}
|
||||||
disabled={resources.length === 0 || loading}
|
disabled={resources.length === 0 || loading || batchDownloading}
|
||||||
onClick={handleBatchDownload}
|
onClick={handleBatchDownload}
|
||||||
|
title={batchDownloading ? `正在打包下载中...` : '批量下载为ZIP'}
|
||||||
>
|
>
|
||||||
下载全部文件
|
{batchDownloading ? (() => {
|
||||||
|
const batchProgress = Array.from(downloadingFiles.values()).find(
|
||||||
|
d => typeof d.fileId === 'string' && d.fileId === 'batch_all'
|
||||||
|
);
|
||||||
|
if (batchProgress) {
|
||||||
|
return `打包中... ${batchProgress.progress}%`;
|
||||||
|
}
|
||||||
|
return `打包中... ${batchDownloadProgress}%`;
|
||||||
|
})() : '批量下载'}
|
||||||
</Button>,
|
</Button>,
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -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 {
|
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 +384,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