refactor(music-houduan): 重构文件上传功能并优化配置

- 更新 sa-token 版本至 1.43.0
- 重构文件上传功能,支持相对路径和绝对路径- 优化文件删除逻辑,处理多种路径情况
- 更新应用配置,使用相对路径
-调整 Redis 配置结构- 移除冗余代码,提高代码可读性
This commit is contained in:
ikmkj
2025-07-23 20:47:18 +08:00
parent b275ffab5a
commit b7fed8b7b7
12 changed files with 108 additions and 61 deletions

View File

@@ -1,5 +1,6 @@
package com.test.musichouduan.service.impl;
import com.test.musichouduan.dto.Result;
import com.test.musichouduan.exception.BusinessException;
import com.test.musichouduan.service.FileService;
import org.slf4j.Logger;
@@ -106,17 +107,47 @@ public class FileServiceImpl implements FileService {
return false;
}
// 从URL中提取文件路径
String filePath = url.replace(accessPath, "");
Path path = Paths.get(uploadPath, filePath);
try {
// 如果是完整URL则只提取路径部分
String filePath = url;
if (url.startsWith("http")) {
// 找到访问路径在URL中的位置
int accessPathIndex = url.indexOf(accessPath);
if (accessPathIndex != -1) {
filePath = url.substring(accessPathIndex);
}
} else {
// 如果不是完整URL确保使用正确的访问路径
filePath = url.replace(accessPath, "");
}
// 确保filePath以accessPath开头
if (!filePath.startsWith(accessPath)) {
filePath = accessPath + filePath;
}
// 从URL中提取文件路径部分去掉访问路径前缀
String fileRelativePath = filePath.replace(accessPath, "");
Path path = Paths.get(uploadPath, fileRelativePath);
// 删除文件
return Files.deleteIfExists(path);
} catch (IOException e) {
logger.error("删除文件失败", e);
} catch (Exception e) {
logger.error("删除文件失败: " + url, e);
return false;
}
//
// // 从URL中提取文件路径
// String filePath = url.replace(accessPath, "");
// Path path = Paths.get(uploadPath, filePath);
//
// try {
// // 删除文件
// return Files.deleteIfExists(path);
// } catch (IOException e) {
// logger.error("删除文件失败", e);
// return false;
// }
}
/**
@@ -132,17 +163,30 @@ public class FileServiceImpl implements FileService {
String extension = getFileExtension(originalFilename);
String fileName = UUID.randomUUID().toString() + "." + extension;
// 创建目录
File dir = new File(uploadPath + directory);
if (!dir.exists()) {
dir.mkdirs();
// // 创建目录
// File dir = new File(uploadPath + directory);
// if (!dir.exists()) {
// dir.mkdirs();
// }
File root = new File(uploadPath); // /uploads
File bizDir = new File(root, directory); // /uploads/bizType
if (!bizDir.exists()) {
boolean ok = bizDir.mkdirs(); // 递归创建
if (!ok) {
Result.error(500, "无法创建目录: " + bizDir.getAbsolutePath());
}
}
File targetFile = new File(bizDir, fileName);
// 保存文件
try {
Path path = Paths.get(uploadPath, directory, fileName);
Files.write(path, file.getBytes());
return "http://localhost:8085" + accessPath + directory + "/" + fileName;
file.transferTo(targetFile);
// Path path = Paths.get(uploadPath, directory, fileName);
// Files.write(path, file.getBytes());
return accessPath+directory + "/" + fileName;
} catch (IOException e) {
logger.error("上传文件失败", e);
throw new BusinessException("上传文件失败");