This commit is contained in:
LiJianZhao 2025-05-17 09:54:37 +08:00
parent ca9ac3413f
commit 9c50980dc8
2 changed files with 20 additions and 2 deletions

1
.gitignore vendored
View File

@ -31,6 +31,7 @@ build/
test_json
logs
logs/*
uploads
### VS Code ###
.vscode/

View File

@ -27,7 +27,7 @@ public class FileService extends BaseService {
}
try {
// 保存文件到指定路径
String uploadPath = "D:/uploads/";
String uploadPath = getJarDirectory() + File.separator + "uploads" + File.separator;
Path dir = Path.of(uploadPath);
// 如果目录不存在则创建目录
if (!Files.exists(dir)) {
@ -42,6 +42,22 @@ public class FileService extends BaseService {
}
}
public String getJarDirectory() {
try {
// 获取当前类所在的 JAR 文件路径
String path = FileService.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
if (path.endsWith(".jar")) {
// 如果是 JAR 返回 JAR 所在目录
return new File(path).getParent();
} else {
// 如果是开发环境 JAR返回项目根目录或其他合适的路径
return new File("").getAbsolutePath();
}
} catch (Exception e) {
throw new RuntimeException("无法获取 JAR 文件路径", e);
}
}
private String generateTempFileName(MultipartFile file) {
// 获取文件的后缀名
String originalFilename = file.getOriginalFilename();
@ -60,7 +76,8 @@ public class FileService extends BaseService {
}
try {
// 指定文件保存的目录
Path uploadPath = Paths.get("D:/uploads/");
String PathStr = getJarDirectory() + File.separator + "uploads" + File.separator;
Path uploadPath = Paths.get(PathStr);
// 构建完整的文件路径
Path filePath = uploadPath.resolve(fileName);