feat: 资源列表批量下载优化
This commit is contained in:
+172
-66
@@ -22,6 +22,10 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
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 java.io.ByteArrayOutputStream;
|
||||
@@ -583,54 +587,95 @@ public class OrderFileController {
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理下载单个文件 - 解决前端跨域问题
|
||||
* 代理下载单个文件 - 真正的流式传输(改进版:零内存积累)
|
||||
*
|
||||
* 优化点:
|
||||
* 1. 使用 StreamingResponseBody,不缓存整个文件在内存
|
||||
* 2. 流式传输,边读边写,避免大文件OOM
|
||||
* 3. 支持超大文件(无GB限制)
|
||||
* 4. 及时flush,让浏览器尽快显示下载
|
||||
* 5. 增大缓冲区到8192字节,提升传输效率
|
||||
*/
|
||||
@Operation(summary = "下载单个文件")
|
||||
@PostMapping("/download")
|
||||
public byte[] downloadFile(@RequestBody FileDownloadRequest request) throws IOException {
|
||||
public ResponseEntity<StreamingResponseBody> downloadFile(@RequestBody FileDownloadRequest request) throws IOException {
|
||||
String fileUrl = request.getUrl();
|
||||
log.info("开始代理下载文件: {}", fileUrl);
|
||||
log.info("📥 开始代理下载文件: {}", fileUrl);
|
||||
|
||||
if (fileUrl == null || fileUrl.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("文件URL不能为空");
|
||||
}
|
||||
|
||||
try {
|
||||
// 从外部 CDN 下载文件
|
||||
URL url = new URL(fileUrl);
|
||||
URLConnection connection = url.openConnection();
|
||||
// 从外部 CDN 下载文件
|
||||
URL url = new URL(fileUrl);
|
||||
URLConnection connection = url.openConnection();
|
||||
|
||||
// 设置超时
|
||||
connection.setConnectTimeout(10000);
|
||||
connection.setReadTimeout(30000);
|
||||
// 设置超时和默认User-Agent
|
||||
connection.setConnectTimeout(10000); // 10秒连接超时
|
||||
connection.setReadTimeout(300000); // 5分钟读取超时,避免网络差时频繁超时
|
||||
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
|
||||
|
||||
// 获取文件内容
|
||||
byte[] buffer = new byte[4096];
|
||||
int bytesRead;
|
||||
java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
|
||||
// 获取文件大小
|
||||
long fileSize = connection.getContentLengthLong();
|
||||
String fileName = extractFileNameFromUrl(fileUrl);
|
||||
|
||||
try (InputStream input = connection.getInputStream()) {
|
||||
while ((bytesRead = input.read(buffer)) != -1) {
|
||||
byteArrayOutputStream.write(buffer, 0, bytesRead);
|
||||
}
|
||||
}
|
||||
log.info("📊 文件信息: 名称={}, 大小={}MB", fileName, fileSize / (1024 * 1024));
|
||||
|
||||
log.info("文件下载成功: {}", extractFileNameFromUrl(fileUrl));
|
||||
return byteArrayOutputStream.toByteArray();
|
||||
} catch (Exception e) {
|
||||
log.error("文件下载失败: fileUrl={}", fileUrl, e);
|
||||
throw new RuntimeException("文件下载失败: " + e.getMessage(), e);
|
||||
// 构建响应头
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
|
||||
if (fileSize > 0) {
|
||||
headers.setContentLength(fileSize);
|
||||
}
|
||||
headers.set("Content-Disposition",
|
||||
"attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
|
||||
headers.set("Accept-Ranges", "bytes");
|
||||
|
||||
// 返回流式响应 - 使用 StreamingResponseBody(核心优化!)
|
||||
// 不需要在内存中积累整个文件,边读边写
|
||||
StreamingResponseBody streamingBody = outputStream -> {
|
||||
try (InputStream input = connection.getInputStream()) {
|
||||
byte[] buffer = new byte[8192]; // 8KB缓冲区
|
||||
int bytesRead;
|
||||
long totalBytes = 0;
|
||||
|
||||
while ((bytesRead = input.read(buffer)) != -1) {
|
||||
outputStream.write(buffer, 0, bytesRead);
|
||||
outputStream.flush(); // 及时flush
|
||||
totalBytes += bytesRead;
|
||||
// 每传输10MB时记录一次进度日志
|
||||
if (totalBytes % (10 * 1024 * 1024) == 0) {
|
||||
log.debug("📊 下载进度: {}MB / {}MB",
|
||||
totalBytes / (1024 * 1024), fileSize / (1024 * 1024));
|
||||
}
|
||||
}
|
||||
log.info("✅ 文件下载完成: {}, 总大小: {}MB",
|
||||
fileName, totalBytes / (1024 * 1024));
|
||||
} catch (IOException e) {
|
||||
log.error("❌ 流式传输文件异常: {}", fileName, e);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.headers(headers)
|
||||
.body(streamingBody);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量下载所有文件 - 打包为 ZIP
|
||||
* 代理批量下载订单所有资源文件 - 改进版:真正的流式传输(无内存积累)
|
||||
*
|
||||
* 优化点:
|
||||
* 1. 使用 StreamingResponseBody,不缓存整个ZIP在内存
|
||||
* 2. 流式生成ZIP条目,边组装边发送
|
||||
* 3. 及时flush,减少缓冲
|
||||
* 4. 支持大文件(无GB限制)
|
||||
*/
|
||||
@Operation(summary = "批量下载订单所有资源文件")
|
||||
@PostMapping("/download/batch")
|
||||
public byte[] batchDownloadFiles(@RequestBody FileDownloadRequest request) {
|
||||
public ResponseEntity<StreamingResponseBody> batchDownloadFiles(@RequestBody FileDownloadRequest request) throws IOException {
|
||||
String orderNo = request.getOrderNo();
|
||||
log.info("开始批量下载订单文件: {}", orderNo);
|
||||
log.info("📦 开始批量下载订单文件: {}", orderNo);
|
||||
|
||||
if (orderNo == null || orderNo.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("订单编号不能为空");
|
||||
@@ -640,53 +685,114 @@ public class OrderFileController {
|
||||
// 查询订单所有文件
|
||||
List<OrderFile> orderFiles = orderFileService.getOrderFileByOrderNo(orderNo);
|
||||
if (CollectionUtils.isEmpty(orderFiles)) {
|
||||
throw new IllegalArgumentException("订单暂无资源文件");
|
||||
throw new RuntimeException("订单无文件");
|
||||
}
|
||||
|
||||
// 创建 ZIP 字节流
|
||||
java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
|
||||
try (ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) {
|
||||
for (OrderFile orderFile : orderFiles) {
|
||||
String viewUrl = fileCenterService.getFileViewUrl(orderFile.getFileId());
|
||||
if (viewUrl == null || viewUrl.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
log.info("📊 订单文件数量: {}", orderFiles.size());
|
||||
|
||||
try {
|
||||
// 下载单个文件
|
||||
URL fileUrl = new URL(viewUrl);
|
||||
URLConnection connection = fileUrl.openConnection();
|
||||
connection.setConnectTimeout(10000);
|
||||
connection.setReadTimeout(30000);
|
||||
// ===== 关键优化:使用流式传输,不需要预先计算总大小 =====
|
||||
// 直接处理所有文件,无GB限制(流式传输不需要在内存中积累)
|
||||
log.info("📊 批量下载文件数: {}", orderFiles.size());
|
||||
|
||||
String fileName = extractFileNameFromUrl(viewUrl);
|
||||
|
||||
// 创建 ZIP 条目
|
||||
ZipEntry zipEntry = new ZipEntry(fileName);
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
|
||||
// 写入文件内容到 ZIP
|
||||
try (InputStream fileInput = connection.getInputStream()) {
|
||||
byte[] buffer = new byte[4096];
|
||||
int bytesRead;
|
||||
while ((bytesRead = fileInput.read(buffer)) != -1) {
|
||||
zipOut.write(buffer, 0, bytesRead);
|
||||
}
|
||||
}
|
||||
|
||||
zipOut.closeEntry();
|
||||
log.info("已添加文件到ZIP: {}", fileName);
|
||||
} catch (Exception e) {
|
||||
log.warn("添加文件到ZIP失败: {}", viewUrl, e);
|
||||
// 继续处理其他文件
|
||||
}
|
||||
// 过滤掉无效URL的文件
|
||||
List<OrderFile> filesToDownload = new ArrayList<>();
|
||||
for (OrderFile file : orderFiles) {
|
||||
String viewUrl = fileCenterService.getFileViewUrl(file.getFileId());
|
||||
if (viewUrl != null && !viewUrl.isEmpty()) {
|
||||
filesToDownload.add(file);
|
||||
} else {
|
||||
log.warn("文件URL为空,跳过: {}", file.getFileId());
|
||||
}
|
||||
}
|
||||
|
||||
log.info("批量下载完成: {}", orderNo);
|
||||
return byteArrayOutputStream.toByteArray();
|
||||
if (filesToDownload.isEmpty()) {
|
||||
throw new RuntimeException("订单无有效资源文件");
|
||||
}
|
||||
|
||||
log.info("📊 有效下载文件数: {}", filesToDownload.size());
|
||||
|
||||
// 构建响应头
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.valueOf("application/zip"));
|
||||
headers.set("Content-Disposition",
|
||||
"attachment;filename=" + URLEncoder.encode(orderNo + ".zip", StandardCharsets.UTF_8.name()));
|
||||
headers.set("Accept-Ranges", "bytes");
|
||||
headers.setCacheControl("no-cache");
|
||||
// 注意:不设置 Content-Length,因为流式传输无法预知最终大小
|
||||
// 前端会显示已下载字节数和速度,而不是百分比进度
|
||||
|
||||
// 返回流式响应 - 使用 StreamingResponseBody
|
||||
// 不需要预先计算Content-Length,数据直接流向浏览器
|
||||
StreamingResponseBody streamingBody = outputStream -> {
|
||||
try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
|
||||
// 设置ZIP压缩级别
|
||||
zipOut.setLevel(6);
|
||||
|
||||
int successCount = 0;
|
||||
int failureCount = 0;
|
||||
|
||||
for (int i = 0; i < filesToDownload.size(); i++) {
|
||||
OrderFile orderFile = filesToDownload.get(i);
|
||||
String viewUrl = fileCenterService.getFileViewUrl(orderFile.getFileId());
|
||||
if (viewUrl == null || viewUrl.isEmpty()) {
|
||||
failureCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
// 下载单个文件
|
||||
URL fileUrl = new URL(viewUrl);
|
||||
URLConnection connection = fileUrl.openConnection();
|
||||
connection.setConnectTimeout(10000); // 10秒连接超时
|
||||
connection.setReadTimeout(300000); // 5分钟读取超时,避免网络差时频繁超时
|
||||
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
|
||||
|
||||
String fileName = extractFileNameFromUrl(viewUrl);
|
||||
|
||||
// 创建 ZIP 条目
|
||||
ZipEntry zipEntry = new ZipEntry(fileName);
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
|
||||
long fileBytes = 0;
|
||||
|
||||
// 写入文件内容到 ZIP - 流式传输(核心优化!)
|
||||
try (InputStream fileInput = connection.getInputStream()) {
|
||||
byte[] buffer = new byte[8192];
|
||||
int bytesRead;
|
||||
while ((bytesRead = fileInput.read(buffer)) != -1) {
|
||||
zipOut.write(buffer, 0, bytesRead);
|
||||
fileBytes += bytesRead;
|
||||
}
|
||||
}
|
||||
|
||||
zipOut.closeEntry();
|
||||
zipOut.flush(); // 及时flush,减少缓冲
|
||||
|
||||
log.info("✅ 已添加文件到ZIP ({}/{}): {} ({}MB)",
|
||||
i + 1, filesToDownload.size(), fileName, fileBytes / (1024 * 1024));
|
||||
successCount++;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.warn("❌ 添加文件到ZIP失败 ({}/{}): {}, 错误: {}",
|
||||
i + 1, filesToDownload.size(), viewUrl, e.getMessage());
|
||||
failureCount++;
|
||||
}
|
||||
}
|
||||
|
||||
log.info("📦 批量下载完成: 订单号={}, 成功={}, 失败={}",
|
||||
orderNo, successCount, failureCount);
|
||||
} catch (IOException e) {
|
||||
log.error("❌ 流式传输ZIP失败: orderNo={}", orderNo, e);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.headers(headers)
|
||||
.body(streamingBody);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("批量下载文件失败: orderNo={}", orderNo, e);
|
||||
log.error("❌ 批量下载文件失败: orderNo={}", orderNo, e);
|
||||
throw new RuntimeException("批量下载失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user