package com.custom.webui.util;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import java.nio.file.Files;
|
import java.nio.file.Path;
|
import java.nio.file.Paths;
|
|
/**
|
* 上传文件的磁盘路径解析工具。
|
*
|
* <p><b>要解决的问题</b>:{@code webui.storage.location} 配置的是相对路径
|
* (默认 {@code ./data/uploads}),相对路径是相对于**进程工作目录**解析的。
|
* 而工作目录会随启动方式变化:
|
*
|
* <pre>
|
* IDE 里以 webui-springboot 为工作目录启动
|
* -> <项目>/webui-springboot/data/uploads
|
* 在项目根目录执行 java -jar
|
* -> <项目>/data/uploads
|
* </pre>
|
*
|
* <p>由于 {@code upload_file.save_path} 记录的是**上传当时的绝对路径**,
|
* 一旦重启时工作目录变了,数据库里的路径就指向一个不存在的位置 ——
|
* 表现为「知识库明明在,但文件读取/删除/重新向量化全部失败」。
|
*
|
* <p><b>解决方式</b>:真正的存储根目录以数据库里已记录的路径为准,
|
* 由 {@link #resolve(Path, String)} 做一次「原路径 → 原路径」的修复:
|
* <ol>
|
* <li>先按记录的绝对路径找,找到就用(绝大多数情况)</li>
|
* <li>找不到时,用文件名在配置的存储根目录下递归搜索,
|
* 命中则用新位置(同时调用方可回写数据库修正记录)</li>
|
* <li>都找不到就返回原路径,让调用方报出原本的错误信息</li>
|
* </ol>
|
*
|
* <p>为什么不把 save_path 改成相对路径:那需要数据迁移,
|
* 且会让「文件实际存放在哪」变得不直观。这里的兜底对存量数据同样有效,
|
* 无需任何迁移。
|
*/
|
@Slf4j
|
public final class StoragePathUtil {
|
|
private StoragePathUtil() {
|
}
|
|
/**
|
* 解析上传文件的实际磁盘路径。
|
*
|
* @param configuredRoot 配置的存储根目录({@code webui.storage.location})
|
* @param storedPath 数据库里记录的 save_path
|
* @return 实际存在的路径;都找不到时返回按 storedPath 构造的路径(可能不存在)
|
*/
|
public static Path resolve(Path configuredRoot, String storedPath) {
|
if (storedPath == null || storedPath.isBlank()) {
|
return configuredRoot;
|
}
|
|
// 1) 原路径可用(最常见)
|
Path original = Paths.get(storedPath);
|
if (Files.exists(original)) {
|
return original;
|
}
|
|
// 2) 原路径失效:按文件名在配置的存储根目录下找
|
Path fileName = original.getFileName();
|
if (fileName == null || configuredRoot == null || !Files.isDirectory(configuredRoot)) {
|
return original;
|
}
|
|
try (var stream = Files.walk(configuredRoot, 6)) {
|
Path found = stream
|
.filter(Files::isRegularFile)
|
.filter(p -> p.getFileName().equals(fileName))
|
.findFirst()
|
.orElse(null);
|
if (found != null) {
|
log.warn("存储路径已失效,已在配置目录下找到同名文件并改用之。"
|
+ "原路径={} 实际路径={}(通常是启动时工作目录变化导致)",
|
storedPath, found);
|
return found;
|
}
|
} catch (Exception e) {
|
log.debug("按文件名搜索失败: {}", e.getMessage());
|
}
|
|
return original;
|
}
|
}
|