feat: onlinePreview 接口中,URL 指向的公网文件过大导致下载缓慢,但这些文件实际就存放在当前服务器的 /home/img 目录下,需要优先使用本地文件
This commit is contained in:
@@ -25,9 +25,12 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@@ -49,6 +52,7 @@ public class OnlinePreviewController {
|
||||
private static final String URL_PARAM_FTP_PASSWORD = "ftp.password";
|
||||
private static final String URL_PARAM_FTP_CONTROL_ENCODING = "ftp.control.encoding";
|
||||
private static final String URL_PARAM_FTP_PORT = "ftp.control.port";
|
||||
private static final String LOCAL_FILE_ROOT = "/home/img";
|
||||
|
||||
private final FilePreviewFactory previewFactory;
|
||||
private final CacheService cacheService;
|
||||
@@ -82,6 +86,8 @@ public class OnlinePreviewController {
|
||||
String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, "url");
|
||||
return otherFilePreview.notSupportedFile(model, errorMsg);
|
||||
}
|
||||
// 优先检查本地文件,本地存在则直接使用,避免从公网下载大文件
|
||||
fileUrl = checkLocalFile(fileUrl);
|
||||
FileAttribute fileAttribute = fileHandlerService.getFileAttribute(fileUrl, req);
|
||||
|
||||
highlightall= KkFileUtils.htmlEscape(highlightall);
|
||||
@@ -287,4 +293,31 @@ public class OnlinePreviewController {
|
||||
cacheService.addQueueTask(fileUrls);
|
||||
return "success";
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查本地是否已有该文件,若有则返回本地文件路径,避免从公网重复下载
|
||||
*
|
||||
* @param fileUrl 解码后的文件URL
|
||||
* @return 本地文件路径(如果存在),否则返回原始URL
|
||||
*/
|
||||
private String checkLocalFile(String fileUrl) {
|
||||
if (fileUrl == null || (!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"))) {
|
||||
return fileUrl;
|
||||
}
|
||||
try {
|
||||
URL url = new URL(fileUrl);
|
||||
String path = url.getPath();
|
||||
if (path != null && !path.isEmpty()) {
|
||||
String decodedPath = URLDecoder.decode(path, StandardCharsets.UTF_8);
|
||||
File localFile = new File(LOCAL_FILE_ROOT, decodedPath);
|
||||
if (localFile.exists() && localFile.isFile()) {
|
||||
logger.info("本地文件存在,使用本地文件:{}", localFile.getAbsolutePath());
|
||||
return "file://" + localFile.getAbsolutePath();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("检查本地文件失败,url:{}", fileUrl, e);
|
||||
}
|
||||
return fileUrl;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user