fix[project]: 同步待办时,下载待办的报告文件

This commit is contained in:
2026-03-23 16:41:08 +08:00
parent 54b4467ef3
commit 6418c89d3a
5 changed files with 237 additions and 0 deletions

View File

@@ -6,6 +6,8 @@ import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.MappedByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
@@ -582,4 +584,115 @@ public class FilesUtil {
}
}
/**
* 从指定URL下载文件到本地
* @param fileUrl 远程文件的URL地址
* @param savePath 本地保存路径(包含文件名,例如:/opt/demand/report/有限元仿真结果报告.pdf
* @throws IOException 处理IO异常
*/
public static void downloadFile(String fileUrl, String savePath) throws IOException {
createDirectoryIfNotExists(savePath);
// 声明连接和流对象
HttpURLConnection connection = null;
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
// 1. 创建URL对象
URL url = new URL(fileUrl);
// 2. 打开连接并设置属性
connection = (HttpURLConnection) url.openConnection();
// 设置连接超时时间5秒
connection.setConnectTimeout(5000);
// 设置读取超时时间10秒
connection.setReadTimeout(10000);
// 设置请求方法
connection.setRequestMethod("GET");
// 允许输入流
connection.setDoInput(true);
// 3. 检查响应码200表示成功
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new IOException("下载失败HTTP响应码" + responseCode);
}
// 4. 获取文件大小(用于进度显示)
long fileSize = connection.getContentLengthLong();
log.info("文件大小:{}", formatFileSize(fileSize));
// 5. 创建输入输出流
in = new BufferedInputStream(connection.getInputStream());
out = new BufferedOutputStream(new FileOutputStream(savePath));
// 6. 缓冲区读写数据
byte[] buffer = new byte[4096]; // 4KB缓冲区
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
log.info("文件下载完成!保存路径:{}",savePath);
} finally {
// 7. 关闭所有流和连接,确保资源释放
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
}
/**
* 格式化文件大小显示字节转KB/MB
* @param size 字节数
* @return 格式化后的大小字符串
*/
private static String formatFileSize(long size) {
if (size < 1024) {
return size + " B";
} else if (size < 1024 * 1024) {
return String.format("%.2f KB", size / 1024.0);
} else {
return String.format("%.2f MB", size / (1024.0 * 1024.0));
}
}
/**
* 解析保存路径,创建不存在的目录
* @param savePath 完整的文件保存路径
*/
private static void createDirectoryIfNotExists(String savePath) {
// 1. 创建File对象
File file = new File(savePath);
// 2. 获取文件所在的目录(去掉文件名部分)
File parentDir = file.getParentFile();
// 3. 如果目录不为空且不存在则创建mkdirs会创建多级目录
if (parentDir != null && !parentDir.exists()) {
boolean isCreated = parentDir.mkdirs();
if (isCreated) {
log.info("目录不存在,已自动创建:" + parentDir.getAbsolutePath());
} else {
log.error("创建目录失败:" + parentDir.getAbsolutePath());
}
}
}
}