mirror of
https://gitee.com/kekingcn/file-online-preview.git
synced 2026-11-12 14:20:40 +00:00
新增 页码定位 美化前端 其他功能调整等
This commit is contained in:
@@ -56,44 +56,44 @@ public class CadToPdfService {
|
||||
* @param fileAttribute 文件属性
|
||||
* @return 转换结果的CompletableFuture
|
||||
*/
|
||||
public CompletableFuture<Boolean> cadToPdfAsync(String inputFilePath, String outputFilePath,
|
||||
public CompletableFuture<Boolean> cadToPdfAsync(String inputFilePath, String outputFilePath,String cacheName,
|
||||
String cadPreviewType, FileAttribute fileAttribute) {
|
||||
String fileName = new File(inputFilePath).getName();
|
||||
|
||||
// 立即创建初始状态,防止重复执行
|
||||
FileConvertStatusManager.startConvert(fileName);
|
||||
FileConvertStatusManager.startConvert(cacheName);
|
||||
// 创建可取消的任务
|
||||
CompletableFuture<Boolean> taskFuture = new CompletableFuture<>();
|
||||
taskCompletionStatus.put(fileName, new AtomicBoolean(false));
|
||||
taskCompletionStatus.put(cacheName, new AtomicBoolean(false));
|
||||
|
||||
// 提交任务到线程池
|
||||
Future<?> future = virtualThreadExecutor.submit(() -> {
|
||||
try {
|
||||
// 添加初始状态更新
|
||||
FileConvertStatusManager.updateProgress(fileName, "正在启动转换任务", 5);
|
||||
boolean result = convertCadWithConcurrencyControl(inputFilePath, outputFilePath,
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在启动转换任务", 5);
|
||||
boolean result = convertCadWithConcurrencyControl(inputFilePath, outputFilePath,cacheName,
|
||||
cadPreviewType, fileAttribute);
|
||||
if (result) {
|
||||
taskFuture.complete(true);
|
||||
taskCompletionStatus.get(fileName).set(true);
|
||||
taskCompletionStatus.get(cacheName).set(true);
|
||||
} else {
|
||||
taskFuture.complete(false);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("CAD转换任务执行失败: {}", fileName, e);
|
||||
FileConvertStatusManager.markError(fileName, "转换过程异常: " + e.getMessage());
|
||||
logger.error("CAD转换任务执行失败: {}", cacheName, e);
|
||||
FileConvertStatusManager.markError(cacheName, "转换过程异常: " + e.getMessage());
|
||||
taskFuture.completeExceptionally(e);
|
||||
} finally {
|
||||
// 移除任务记录
|
||||
runningTasks.remove(fileName);
|
||||
taskCompletionStatus.remove(fileName);
|
||||
runningTasks.remove(cacheName);
|
||||
taskCompletionStatus.remove(cacheName);
|
||||
}
|
||||
});
|
||||
|
||||
// 记录正在运行的任务
|
||||
runningTasks.put(fileName, future);
|
||||
runningTasks.put(cacheName, future);
|
||||
|
||||
// 设置超时取消
|
||||
scheduleTimeoutCheck(fileName, taskFuture, future, outputFilePath);
|
||||
scheduleTimeoutCheck(cacheName, taskFuture, future, outputFilePath);
|
||||
|
||||
return taskFuture;
|
||||
}
|
||||
@@ -160,34 +160,34 @@ public class CadToPdfService {
|
||||
/**
|
||||
* 带并发控制的CAD转换
|
||||
*/
|
||||
private boolean convertCadWithConcurrencyControl(String inputFilePath, String outputFilePath,
|
||||
private boolean convertCadWithConcurrencyControl(String inputFilePath, String outputFilePath,String cacheName,
|
||||
String cadPreviewType, FileAttribute fileAttribute)
|
||||
throws Exception {
|
||||
String fileName = new File(inputFilePath).getName();
|
||||
|
||||
long acquireStartTime = System.currentTimeMillis();
|
||||
|
||||
// 获取并发许可
|
||||
if (!concurrentLimit.tryAcquire(30, TimeUnit.SECONDS)) {
|
||||
long acquireTime = System.currentTimeMillis() - acquireStartTime;
|
||||
logger.warn("获取并发许可超时,文件: {}, 等待时间: {}ms", fileName, acquireTime);
|
||||
FileConvertStatusManager.updateProgress(fileName, "系统繁忙,等待资源中...", 15);
|
||||
logger.warn("获取并发许可超时,文件: {}, 等待时间: {}ms", cacheName, acquireTime);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "系统繁忙,等待资源中...", 15);
|
||||
throw new TimeoutException("系统繁忙,请稍后重试");
|
||||
}
|
||||
|
||||
long acquireTime = System.currentTimeMillis() - acquireStartTime;
|
||||
logger.debug("获取并发许可成功: {}, 等待时间: {}ms", fileName, acquireTime);
|
||||
logger.debug("获取并发许可成功: {}, 等待时间: {}ms", cacheName, acquireTime);
|
||||
|
||||
// 更新状态
|
||||
FileConvertStatusManager.updateProgress(fileName, "已获取转换资源,开始转换", 20);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "已获取转换资源,开始转换", 20);
|
||||
|
||||
long conversionStartTime = System.currentTimeMillis();
|
||||
|
||||
try {
|
||||
boolean result = performCadConversion(inputFilePath, outputFilePath, cadPreviewType, fileAttribute);
|
||||
boolean result = performCadConversion(inputFilePath, outputFilePath,cacheName, cadPreviewType, fileAttribute);
|
||||
|
||||
long conversionTime = System.currentTimeMillis() - conversionStartTime;
|
||||
logger.debug("CAD转换核心完成: {}, 转换耗时: {}ms, 总耗时(含等待): {}ms",
|
||||
fileName, conversionTime, conversionTime + acquireTime);
|
||||
cacheName, conversionTime, conversionTime + acquireTime);
|
||||
|
||||
return result;
|
||||
|
||||
@@ -199,49 +199,48 @@ public class CadToPdfService {
|
||||
/**
|
||||
* 执行实际的CAD转换逻辑
|
||||
*/
|
||||
private boolean performCadConversion(String inputFilePath, String outputFilePath,
|
||||
private boolean performCadConversion(String inputFilePath, String outputFilePath,String cacheName,
|
||||
String cadPreviewType, FileAttribute fileAttribute) {
|
||||
final InterruptionTokenSource source = new InterruptionTokenSource();
|
||||
String fileName = new File(inputFilePath).getName();
|
||||
long totalStartTime = System.currentTimeMillis();
|
||||
try {
|
||||
// 1. 验证输入参数
|
||||
long validationStartTime = System.currentTimeMillis();
|
||||
FileConvertStatusManager.updateProgress(fileName, "正在验证文件参数", 25);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在验证文件参数", 25);
|
||||
if (!validateInputParameters(inputFilePath, outputFilePath, cadPreviewType)) {
|
||||
long validationTime = System.currentTimeMillis() - validationStartTime;
|
||||
logger.error("CAD转换参数验证失败: {}, 验证耗时: {}ms", fileName, validationTime);
|
||||
FileConvertStatusManager.markError(fileName, "文件参数验证失败");
|
||||
logger.error("CAD转换参数验证失败: {}, 验证耗时: {}ms", cacheName, validationTime);
|
||||
FileConvertStatusManager.markError(cacheName, "文件参数验证失败");
|
||||
return false;
|
||||
}
|
||||
long validationTime = System.currentTimeMillis() - validationStartTime;
|
||||
|
||||
// 2. 创建输出目录
|
||||
long directoryStartTime = System.currentTimeMillis();
|
||||
FileConvertStatusManager.updateProgress(fileName, "正在准备输出目录", 30);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在准备输出目录", 30);
|
||||
createOutputDirectoryIfNeeded(outputFilePath, fileAttribute.isCompressFile());
|
||||
long directoryTime = System.currentTimeMillis() - directoryStartTime;
|
||||
|
||||
// 3. 加载并转换CAD文件
|
||||
long loadStartTime = System.currentTimeMillis();
|
||||
FileConvertStatusManager.updateProgress(fileName, "正在加载CAD文件", 40);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在加载CAD文件", 40);
|
||||
LoadOptions loadOptions = createLoadOptions();
|
||||
|
||||
try (Image cadImage = Image.load(inputFilePath, loadOptions)) {
|
||||
long loadTime = System.currentTimeMillis() - loadStartTime;
|
||||
logger.debug("CAD文件加载完成: {}, 加载耗时: {}ms", fileName, loadTime);
|
||||
logger.debug("CAD文件加载完成: {}, 加载耗时: {}ms", cacheName, loadTime);
|
||||
|
||||
FileConvertStatusManager.updateProgress(fileName, "CAD文件加载完成,开始渲染", 50);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "CAD文件加载完成,开始渲染", 50);
|
||||
|
||||
// 4. 创建光栅化选项
|
||||
long rasterizationStartTime = System.currentTimeMillis();
|
||||
FileConvertStatusManager.updateProgress(fileName, "正在设置渲染参数", 60);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在设置渲染参数", 60);
|
||||
CadRasterizationOptions rasterizationOptions = createRasterizationOptions(cadImage);
|
||||
long rasterizationTime = System.currentTimeMillis() - rasterizationStartTime;
|
||||
|
||||
// 5. 根据预览类型创建选项
|
||||
long optionsStartTime = System.currentTimeMillis();
|
||||
FileConvertStatusManager.updateProgress(fileName, "正在配置输出格式", 70);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在配置输出格式", 70);
|
||||
var options = switch (cadPreviewType.toLowerCase()) {
|
||||
case "svg" -> createSvgOptions(rasterizationOptions, source);
|
||||
case "pdf" -> createPdfOptions(rasterizationOptions, source);
|
||||
@@ -251,15 +250,15 @@ public class CadToPdfService {
|
||||
long optionsTime = System.currentTimeMillis() - optionsStartTime;
|
||||
// 6. 保存转换结果
|
||||
long saveStartTime = System.currentTimeMillis();
|
||||
FileConvertStatusManager.updateProgress(fileName, "正在生成输出文件", 80);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在生成输出文件", 80);
|
||||
saveConvertedFile(outputFilePath, cadImage, options);
|
||||
long saveTime = System.currentTimeMillis() - saveStartTime;
|
||||
FileConvertStatusManager.updateProgress(fileName, "文件转换完成", 90);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "文件转换完成", 90);
|
||||
// 计算总时间
|
||||
long totalTime = System.currentTimeMillis() - totalStartTime;
|
||||
// 记录详细的性能信息
|
||||
logger.debug("CAD转换详细耗时 - 文件: {}, 验证={}ms, 目录={}ms, 加载={}ms, 光栅化={}ms, 选项={}ms, 保存={}ms, 总耗时={}ms",
|
||||
fileName, validationTime, directoryTime, loadTime,
|
||||
cacheName, validationTime, directoryTime, loadTime,
|
||||
rasterizationTime, optionsTime, saveTime, totalTime);
|
||||
|
||||
logger.info("CAD转换完成: 总耗时: {}ms", totalTime);
|
||||
@@ -272,9 +271,9 @@ public class CadToPdfService {
|
||||
}
|
||||
|
||||
// 转换成功,标记为完成
|
||||
FileConvertStatusManager.updateProgress(fileName, "转换成功", 100);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "转换成功", 100);
|
||||
// 短暂延迟后清理状态,给前端一个显示100%的机会
|
||||
FileConvertStatusManager.convertSuccess(fileName);
|
||||
FileConvertStatusManager.convertSuccess(cacheName);
|
||||
|
||||
|
||||
return true;
|
||||
@@ -282,12 +281,12 @@ public class CadToPdfService {
|
||||
|
||||
} catch (Exception e) {
|
||||
long totalTime = System.currentTimeMillis() - totalStartTime;
|
||||
logger.error("CAD转换执行失败: {}, 耗时: {}ms", fileName, totalTime, e);
|
||||
logger.error("CAD转换执行失败: {}, 耗时: {}ms", cacheName, totalTime, e);
|
||||
|
||||
// 检查是否已经标记为超时
|
||||
FileConvertStatusManager.ConvertStatus status = FileConvertStatusManager.getConvertStatus(fileName);
|
||||
FileConvertStatusManager.ConvertStatus status = FileConvertStatusManager.getConvertStatus(cacheName);
|
||||
if (status == null || status.getStatus() != FileConvertStatusManager.Status.TIMEOUT) {
|
||||
FileConvertStatusManager.markError(fileName, "转换失败: " + e.getMessage());
|
||||
FileConvertStatusManager.markError(cacheName, "转换失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
// 删除可能已创建的不完整文件
|
||||
@@ -302,7 +301,7 @@ public class CadToPdfService {
|
||||
long cleanupTime = System.currentTimeMillis() - cleanupStartTime;
|
||||
long totalTime = System.currentTimeMillis() - totalStartTime;
|
||||
logger.debug("CAD转换资源清理完成: {}, 清理耗时: {}ms, 总耗时: {}ms",
|
||||
fileName, cleanupTime, totalTime);
|
||||
cacheName, cleanupTime, totalTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,10 +254,16 @@ public class FileHandlerService {
|
||||
try {
|
||||
originFileName = URLDecoder.decode(originFileName, uriEncoding); //转义的文件名 解下出原始文件名
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
logger.error("Failed to decode file name: {}", originFileName, e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}else {
|
||||
url = WebUtils.encodeUrlFileName(url); //对未转义的url进行转义
|
||||
url = Objects.requireNonNull(WebUtils.encodeUrlFileName(url))
|
||||
.replaceAll("\\+", "%20")
|
||||
.replaceAll("%3A", ":")
|
||||
.replaceAll("%2F", "/")
|
||||
.replaceAll("%3F", "?")
|
||||
.replaceAll("%26", "&")
|
||||
.replaceAll("%3D", "=");
|
||||
}
|
||||
originFileName = KkFileUtils.htmlEscape(originFileName); //文件名处理
|
||||
boolean isHtmlView = suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx") || suffix.equalsIgnoreCase("csv") || suffix.equalsIgnoreCase("xlsm") || suffix.equalsIgnoreCase("xlt") || suffix.equalsIgnoreCase("xltm") || suffix.equalsIgnoreCase("et") || suffix.equalsIgnoreCase("ett") || suffix.equalsIgnoreCase("xlam");
|
||||
|
||||
@@ -2,6 +2,7 @@ package cn.keking.service;
|
||||
|
||||
import cn.keking.config.ConfigConstants;
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.utils.FileConvertStatusManager;
|
||||
import org.bytedeco.ffmpeg.global.avcodec;
|
||||
import org.bytedeco.javacv.FFmpegFrameGrabber;
|
||||
import org.bytedeco.javacv.FFmpegFrameRecorder;
|
||||
@@ -12,7 +13,6 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
@@ -89,15 +89,17 @@ public class Mediatomp4Service {
|
||||
* 异步转换方法(带任务ID和超时控制)
|
||||
*/
|
||||
public static CompletableFuture<Boolean> convertToMp4Async(
|
||||
String filePath, String outFilePath, FileAttribute fileAttribute) {
|
||||
String filePath, String outFilePath,String cacheName, FileAttribute fileAttribute) {
|
||||
|
||||
String taskId = generateTaskId(filePath);
|
||||
// 立即创建初始状态,防止重复执行
|
||||
FileConvertStatusManager.startConvert(cacheName);
|
||||
CompletableFuture<Boolean> resultFuture = new CompletableFuture<>();
|
||||
|
||||
// 创建转换线程
|
||||
Thread conversionThread = new Thread(() -> {
|
||||
try {
|
||||
boolean result = convertToMp4WithCancellation(filePath, outFilePath,
|
||||
boolean result = convertToMp4WithCancellation(filePath, outFilePath,cacheName,
|
||||
fileAttribute, taskId, resultFuture);
|
||||
resultFuture.complete(result);
|
||||
} catch (Exception e) {
|
||||
@@ -120,10 +122,11 @@ public class Mediatomp4Service {
|
||||
// 设置超时监控
|
||||
File inputFile = new File(filePath);
|
||||
long fileSizeMB = inputFile.length() / (1024 * 1024);
|
||||
scheduleTimeoutMonitor(taskId, calculateTimeout(fileSizeMB));
|
||||
scheduleTimeoutMonitor(taskId, calculateTimeout(fileSizeMB),cacheName);
|
||||
return resultFuture;
|
||||
|
||||
} catch (Exception e) {
|
||||
FileConvertStatusManager.markError(cacheName, "转换过程异常: " + e.getMessage());
|
||||
resultFuture.completeExceptionally(e);
|
||||
cleanupFailedFile(outFilePath);
|
||||
return resultFuture;
|
||||
@@ -134,25 +137,18 @@ public class Mediatomp4Service {
|
||||
* 带取消支持的同步转换方法(核心改进)
|
||||
*/
|
||||
private static boolean convertToMp4WithCancellation(
|
||||
String filePath, String outFilePath, FileAttribute fileAttribute,
|
||||
String filePath, String outFilePath,String cacheName, FileAttribute fileAttribute,
|
||||
String taskId, CompletableFuture<Boolean> resultFuture) throws Exception {
|
||||
|
||||
FFmpegFrameGrabber frameGrabber = null;
|
||||
FFmpegFrameRecorder recorder = null;
|
||||
ConversionContext context = null;
|
||||
|
||||
try {
|
||||
File sourceFile = new File(filePath);
|
||||
if (!sourceFile.exists()) {
|
||||
throw new FileNotFoundException("源文件不存在: " + filePath);
|
||||
}
|
||||
|
||||
File desFile = new File(outFilePath);
|
||||
if (desFile.exists() && !fileAttribute.forceUpdatedCache()) {
|
||||
logger.info("目标文件已存在,跳过转换: {}", outFilePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在启动转换任务", 10);
|
||||
// 初始化抓取器
|
||||
frameGrabber = new FFmpegFrameGrabber(sourceFile);
|
||||
frameGrabber.setOption("stimeout", "10000000"); // 10秒超时
|
||||
@@ -168,7 +164,7 @@ public class Mediatomp4Service {
|
||||
|
||||
configureRecorder(recorder, frameGrabber);
|
||||
recorder.start();
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在启动转换任务", 40);
|
||||
// 创建任务上下文
|
||||
context = new ConversionContext(frameGrabber, recorder);
|
||||
|
||||
@@ -180,7 +176,7 @@ public class Mediatomp4Service {
|
||||
logger.info("开始转换任务 {}: {} -> {}", taskId, filePath, outFilePath);
|
||||
|
||||
// 核心:使用非阻塞方式读取帧
|
||||
return processFramesWithTimeout(frameGrabber, recorder, context, taskId);
|
||||
return processFramesWithTimeout(frameGrabber, recorder, context, taskId,cacheName);
|
||||
|
||||
} catch (Exception e) {
|
||||
// 检查是否是取消操作
|
||||
@@ -208,7 +204,7 @@ public class Mediatomp4Service {
|
||||
*/
|
||||
private static boolean processFramesWithTimeout(
|
||||
FFmpegFrameGrabber grabber, FFmpegFrameRecorder recorder,
|
||||
ConversionContext context, String taskId) throws Exception {
|
||||
ConversionContext context, String taskId, String cacheName) throws Exception {
|
||||
|
||||
long frameCount = 0;
|
||||
long startTime = System.currentTimeMillis();
|
||||
@@ -227,10 +223,9 @@ public class Mediatomp4Service {
|
||||
logger.warn("任务 {} 帧读取超时,可能文件损坏", taskId);
|
||||
throw new TimeoutException("帧读取超时");
|
||||
}
|
||||
|
||||
// 尝试抓取帧
|
||||
frame = grabber.grabFrame();
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在启动转换任务", 60);
|
||||
if (frame == null) {
|
||||
consecutiveNullFrames++;
|
||||
|
||||
@@ -260,7 +255,7 @@ public class Mediatomp4Service {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在启动转换任务", 80);
|
||||
// 成功获取到帧,重置计数器
|
||||
consecutiveNullFrames = 0;
|
||||
lastFrameTime = System.currentTimeMillis();
|
||||
@@ -295,12 +290,12 @@ public class Mediatomp4Service {
|
||||
// 完成录制
|
||||
recorder.stop();
|
||||
recorder.close();
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在启动转换任务", 100);
|
||||
long totalTime = System.currentTimeMillis() - startTime;
|
||||
double fps = totalTime > 0 ? (frameCount * 1000.0) / totalTime : 0;
|
||||
logger.info("任务 {} 转换完成: {} 帧, 耗时: {}ms, 平均速度: {} fps",
|
||||
taskId, frameCount, totalTime, String.format("%.2f", fps));
|
||||
|
||||
FileConvertStatusManager.convertSuccess(cacheName);
|
||||
return true;
|
||||
|
||||
} catch (Exception e) {
|
||||
@@ -404,11 +399,12 @@ public class Mediatomp4Service {
|
||||
/**
|
||||
* 配置超时监控
|
||||
*/
|
||||
private static void scheduleTimeoutMonitor(String taskId, long timeoutSeconds) {
|
||||
private static void scheduleTimeoutMonitor(String taskId, long timeoutSeconds,String cacheName) {
|
||||
ScheduledFuture<?> timeoutFuture = monitorExecutor.schedule(() -> {
|
||||
ConversionTask task = activeTasks.get(taskId);
|
||||
if (task != null && !task.context.completed) {
|
||||
logger.warn("任务 {} 超时 ({}秒),开始强制终止", taskId, timeoutSeconds);
|
||||
FileConvertStatusManager.markTimeout(cacheName);
|
||||
cancelConversion(taskId);
|
||||
task.future.completeExceptionally(
|
||||
new TimeoutException("转换超时: " + timeoutSeconds + "秒")
|
||||
@@ -471,16 +467,6 @@ public class Mediatomp4Service {
|
||||
throw new FileNotFoundException("源文件不存在: " + filePath);
|
||||
}
|
||||
|
||||
File desFile = new File(outFilePath);
|
||||
if (desFile.exists()) {
|
||||
if (fileAttribute.forceUpdatedCache()) {
|
||||
if (!desFile.delete()) {
|
||||
throw new IOException("无法删除已存在的文件: " + outFilePath);
|
||||
}
|
||||
} else {
|
||||
throw new IllegalStateException("目标文件已存在,跳过转换");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -79,29 +79,20 @@ public class OfficeToPdfService {
|
||||
// 格式化显示耗时(支持不同时间单位)
|
||||
String durationFormatted;
|
||||
if (duration.toMinutes() > 0) {
|
||||
durationFormatted = String.format("%d分%d秒",
|
||||
duration.toMinutes(),
|
||||
duration.toSecondsPart());
|
||||
durationFormatted = String.format("%d分%d秒", duration.toMinutes(), duration.toSecondsPart());
|
||||
} else if (duration.toSeconds() > 0) {
|
||||
durationFormatted = String.format("%d.%03d秒",
|
||||
duration.toSeconds(),
|
||||
duration.toMillisPart());
|
||||
durationFormatted = String.format("%d.%03d秒",duration.toSeconds(), duration.toMillisPart());
|
||||
} else {
|
||||
durationFormatted = String.format("%d毫秒", duration.toMillis());
|
||||
}
|
||||
|
||||
logger.info("文件转换成功:{} -> {},耗时:{}",
|
||||
inputFile.getName(),
|
||||
outputFile.getName(),
|
||||
durationFormatted);
|
||||
inputFile.getName(),outputFile.getName(), durationFormatted);
|
||||
|
||||
} catch (OfficeException e) {
|
||||
Instant endTime = Instant.now();
|
||||
Duration duration = Duration.between(startTime, endTime);
|
||||
logger.error("文件转换失败:{},已耗时:{}毫秒,错误信息:{}",
|
||||
inputFile.getName(),
|
||||
duration.toMillis(),
|
||||
e.getMessage());
|
||||
logger.error("文件转换失败:{},已耗时:{}毫秒,错误信息:{}", inputFile.getName(), duration.toMillis(), e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,7 @@
|
||||
package cn.keking.service;
|
||||
|
||||
import cn.keking.config.ConfigConstants;
|
||||
import cn.keking.utils.FileConvertStatusManager;
|
||||
import cn.keking.utils.WebUtils;
|
||||
import cn.keking.web.filter.BaseUrlFilter;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
@@ -60,14 +61,13 @@ public class TifToPdfService {
|
||||
/**
|
||||
* TIF转JPG - 虚拟线程版本
|
||||
*/
|
||||
public List<String> convertTif2Jpg(String strInputFile, String strOutputFile,
|
||||
public List<String> convertTif2Jpg(String strInputFile, String strOutputFile,String fileName,
|
||||
String cacheName,
|
||||
boolean forceUpdatedCache) throws Exception {
|
||||
String fileName = new File(strInputFile).getName();
|
||||
Instant startTime = Instant.now();
|
||||
|
||||
try {
|
||||
List<String> result = performTifToJpgConversionVirtual(
|
||||
strInputFile, strOutputFile, forceUpdatedCache
|
||||
strInputFile, strOutputFile, forceUpdatedCache,fileName,cacheName
|
||||
);
|
||||
|
||||
Duration elapsedTime = Duration.between(startTime, Instant.now());
|
||||
@@ -90,7 +90,8 @@ public class TifToPdfService {
|
||||
* 虚拟线程执行TIF转JPG转换
|
||||
*/
|
||||
private List<String> performTifToJpgConversionVirtual(String strInputFile, String strOutputFile,
|
||||
boolean forceUpdatedCache) throws Exception {
|
||||
boolean forceUpdatedCache,String fileName,
|
||||
String cacheName) throws Exception {
|
||||
Instant totalStart = Instant.now();
|
||||
|
||||
String baseUrl = BaseUrlFilter.getBaseUrl();
|
||||
@@ -105,7 +106,7 @@ public class TifToPdfService {
|
||||
if (!outputDir.exists() && !outputDir.mkdirs()) {
|
||||
throw new IOException("创建目录失败: " + outputDirPath);
|
||||
}
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在转换TIF为PDF", 30);
|
||||
// 加载所有图片
|
||||
List<BufferedImage> images;
|
||||
try {
|
||||
@@ -121,12 +122,12 @@ public class TifToPdfService {
|
||||
logger.warn("TIF文件没有可转换的页面: {}", strInputFile);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在转换TIF为PDF", 50);
|
||||
List<String> result = convertPagesVirtualThreads(images, outputDirPath, baseUrl, forceUpdatedCache);
|
||||
|
||||
Duration totalTime = Duration.between(totalStart, Instant.now());
|
||||
logger.info("TIF转换PNG完成,总页数: {}, 总耗时: {}ms", pageCount, totalTime.toMillis());
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在转换TIF为PDF", 100);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -211,9 +212,9 @@ public class TifToPdfService {
|
||||
/**
|
||||
* TIF转PDF - 虚拟线程版本
|
||||
*/
|
||||
public void convertTif2Pdf(String strJpgFile, String strPdfFile,
|
||||
public void convertTif2Pdf(String strJpgFile, String strPdfFile,String fileName,
|
||||
String cacheName,
|
||||
boolean forceUpdatedCache) throws Exception {
|
||||
String fileName = new File(strJpgFile).getName();
|
||||
Instant startTime = Instant.now();
|
||||
|
||||
try {
|
||||
@@ -224,8 +225,8 @@ public class TifToPdfService {
|
||||
logger.info("PDF文件已存在,跳过转换: {}", strPdfFile);
|
||||
return;
|
||||
}
|
||||
|
||||
boolean result = performTifToPdfConversionVirtual(strJpgFile, strPdfFile);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在转换TIF为PDF", 30);
|
||||
boolean result = performTifToPdfConversionVirtual(strJpgFile, strPdfFile,fileName,cacheName);
|
||||
Duration elapsedTime = Duration.between(startTime, Instant.now());
|
||||
|
||||
logger.info("TIF转PDF{} - 文件: {}, 耗时: {}ms",
|
||||
@@ -244,7 +245,7 @@ public class TifToPdfService {
|
||||
/**
|
||||
* 虚拟线程执行TIF转PDF转换(保持顺序)
|
||||
*/
|
||||
private boolean performTifToPdfConversionVirtual(String strJpgFile, String strPdfFile) throws Exception {
|
||||
private boolean performTifToPdfConversionVirtual(String strJpgFile, String strPdfFile,String fileName,String cacheName) throws Exception {
|
||||
Instant totalStart = Instant.now();
|
||||
|
||||
File tiffFile = new File(strJpgFile);
|
||||
@@ -257,14 +258,14 @@ public class TifToPdfService {
|
||||
logger.warn("TIFF文件没有可转换的页面: {}", strJpgFile);
|
||||
return false;
|
||||
}
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在转换TIF为PDF", 30);
|
||||
int pageCount = images.size();
|
||||
AtomicInteger processedCount = new AtomicInteger(0);
|
||||
AtomicInteger errorCount = new AtomicInteger(0);
|
||||
|
||||
// 创建页面处理结果的列表
|
||||
List<CompletableFuture<ProcessedPageResult>> futures = new ArrayList<>(pageCount);
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在转换TIF为PDF", 50);
|
||||
// 为每个页面创建处理任务
|
||||
for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
|
||||
final int currentPageIndex = pageIndex;
|
||||
@@ -286,7 +287,7 @@ public class TifToPdfService {
|
||||
|
||||
futures.add(future);
|
||||
}
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在转换TIF为PDF", 70);
|
||||
// 等待所有任务完成
|
||||
CompletableFuture<Void> allFutures = CompletableFuture.allOf(
|
||||
futures.toArray(new CompletableFuture[0])
|
||||
@@ -332,7 +333,7 @@ public class TifToPdfService {
|
||||
errorCount.incrementAndGet();
|
||||
}
|
||||
}
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在转换TIF为PDF", 100);
|
||||
// 保存PDF
|
||||
document.save(strPdfFile);
|
||||
|
||||
|
||||
@@ -55,7 +55,6 @@ public class CadFilePreviewImpl implements FilePreview {
|
||||
// 预览Type,参数传了就取参数的,没传取系统默认
|
||||
String officePreviewType = fileAttribute.getOfficePreviewType() == null ?
|
||||
ConfigConstants.getOfficePreviewType() : fileAttribute.getOfficePreviewType();
|
||||
String baseUrl = BaseUrlFilter.getBaseUrl();
|
||||
boolean forceUpdatedCache = fileAttribute.forceUpdatedCache();
|
||||
String fileName = fileAttribute.getName();
|
||||
String cadPreviewType = ConfigConstants.getCadPreviewType();
|
||||
@@ -63,20 +62,9 @@ public class CadFilePreviewImpl implements FilePreview {
|
||||
String outFilePath = fileAttribute.getOutFilePath();
|
||||
|
||||
// 查询转换状态
|
||||
FileConvertStatusManager.ConvertStatus status = FileConvertStatusManager.getConvertStatus(fileName);
|
||||
if (status != null) {
|
||||
if (status.getStatus() == FileConvertStatusManager.Status.CONVERTING) {
|
||||
// 正在转换中,返回等待页面
|
||||
model.addAttribute("fileName", fileName);
|
||||
model.addAttribute("message", status.getRealTimeMessage());
|
||||
return WAITING_FILE_PREVIEW_PAGE;
|
||||
} else if (status.getStatus() == FileConvertStatusManager.Status.TIMEOUT) {
|
||||
// 超时状态,不允许重新转换
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "文件转换已超时,无法继续转换");
|
||||
} else if (status.getStatus() == FileConvertStatusManager.Status.FAILED) {
|
||||
// 失败状态,不允许重新转换
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "文件转换失败,无法继续转换");
|
||||
}
|
||||
String statusResult = officefilepreviewimpl.checkAndHandleConvertStatus(model, fileName, cacheName, fileAttribute);
|
||||
if (statusResult != null) {
|
||||
return statusResult;
|
||||
}
|
||||
|
||||
// 判断之前是否已转换过,如果转换过,直接返回,否则执行转换
|
||||
@@ -117,6 +105,7 @@ public class CadFilePreviewImpl implements FilePreview {
|
||||
CompletableFuture<Boolean> conversionFuture = cadtopdfservice.cadToPdfAsync(
|
||||
filePath,
|
||||
outFilePath,
|
||||
cacheName,
|
||||
ConfigConstants.getCadPreviewType(),
|
||||
fileAttribute
|
||||
);
|
||||
@@ -166,11 +155,8 @@ public class CadFilePreviewImpl implements FilePreview {
|
||||
|
||||
if (baseUrl != null && (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) ||
|
||||
OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType))) {
|
||||
return officefilepreviewimpl.getPreviewType(model, fileAttribute, officePreviewType,
|
||||
cacheName, outFilePath, fileHandlerService,
|
||||
OFFICE_PREVIEW_TYPE_IMAGE, otherFilePreview);
|
||||
return officefilepreviewimpl.getPreviewType(model, fileAttribute, officePreviewType, cacheName, outFilePath);
|
||||
}
|
||||
|
||||
model.addAttribute("pdfUrl", cacheName);
|
||||
return PDF_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,11 @@ public class CodeFilePreviewImpl implements FilePreview {
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
filePreviewHandle.filePreviewHandle(url, model, fileAttribute);
|
||||
String suffix = fileAttribute.getSuffix();
|
||||
if(suffix.equalsIgnoreCase("htm") || suffix.equalsIgnoreCase("html") || suffix.equalsIgnoreCase("shtml") ){
|
||||
model.addAttribute("pdfUrl", url);
|
||||
return TXT_FILE_PREVIEW_PAGE; //直接输出html
|
||||
}
|
||||
return CODE_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,23 +8,23 @@ import cn.keking.service.FileHandlerService;
|
||||
import cn.keking.service.FilePreview;
|
||||
import cn.keking.service.Mediatomp4Service;
|
||||
import cn.keking.utils.DownloadUtils;
|
||||
import cn.keking.utils.FileConvertStatusManager;
|
||||
import cn.keking.utils.KkFileUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* @author : kl
|
||||
* @authorboke : kailing.pub
|
||||
* @create : 2018-03-25 上午11:58
|
||||
* @description:
|
||||
* @description: 异步视频文件预览实现
|
||||
**/
|
||||
@Service
|
||||
public class MediaFilePreviewImpl implements FilePreview {
|
||||
@@ -32,10 +32,20 @@ public class MediaFilePreviewImpl implements FilePreview {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MediaFilePreviewImpl.class);
|
||||
private final FileHandlerService fileHandlerService;
|
||||
private final OtherFilePreviewImpl otherFilePreview;
|
||||
private final Mediatomp4Service mediatomp4Service;
|
||||
private final OfficeFilePreviewImpl officefilepreviewimpl;
|
||||
|
||||
public MediaFilePreviewImpl(FileHandlerService fileHandlerService, OtherFilePreviewImpl otherFilePreview) {
|
||||
// 用于处理回调的线程池
|
||||
private static final ExecutorService callbackExecutor = Executors.newFixedThreadPool(3);
|
||||
|
||||
public MediaFilePreviewImpl(FileHandlerService fileHandlerService,
|
||||
OtherFilePreviewImpl otherFilePreview,
|
||||
Mediatomp4Service mediatomp4Service,
|
||||
OfficeFilePreviewImpl officefilepreviewimpl) {
|
||||
this.fileHandlerService = fileHandlerService;
|
||||
this.otherFilePreview = otherFilePreview;
|
||||
this.mediatomp4Service = mediatomp4Service;
|
||||
this.officefilepreviewimpl = officefilepreviewimpl;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -46,69 +56,61 @@ public class MediaFilePreviewImpl implements FilePreview {
|
||||
String outFilePath = fileAttribute.getOutFilePath();
|
||||
boolean forceUpdatedCache = fileAttribute.forceUpdatedCache();
|
||||
FileType type = fileAttribute.getType();
|
||||
String[] mediaTypesConvert = FileType.MEDIA_CONVERT_TYPES; //获取支持的转换格式
|
||||
|
||||
// 检查是否是需要转换的视频格式
|
||||
boolean mediaTypes = false;
|
||||
String[] mediaTypesConvert = FileType.MEDIA_CONVERT_TYPES;
|
||||
for (String temp : mediaTypesConvert) {
|
||||
if (suffix.equalsIgnoreCase(temp)) {
|
||||
mediaTypes = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 查询转换状态
|
||||
String statusResult = officefilepreviewimpl.checkAndHandleConvertStatus(model, fileName, cacheName, fileAttribute);
|
||||
if (statusResult != null) {
|
||||
return statusResult;
|
||||
}
|
||||
// 非HTTP协议或需要转换的文件
|
||||
if (!url.toLowerCase().startsWith("http") || checkNeedConvert(mediaTypes)) {
|
||||
// 检查缓存
|
||||
File outputFile = new File(outFilePath);
|
||||
if (outputFile.exists() && !forceUpdatedCache && ConfigConstants.isCacheEnabled()) {
|
||||
String relativePath = fileHandlerService.getRelativePath(outFilePath);
|
||||
if (fileHandlerService.listConvertedFiles().containsKey(cacheName)) {
|
||||
if (fileHandlerService.listConvertedMedias().containsKey(cacheName)) {
|
||||
model.addAttribute("mediaUrl", relativePath);
|
||||
logger.info("使用已缓存的视频文件: {}", cacheName);
|
||||
return MEDIA_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
}
|
||||
|
||||
// 下载文件
|
||||
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName);
|
||||
if (response.isFailure()) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg());
|
||||
}
|
||||
|
||||
String filePath = response.getContent();
|
||||
|
||||
try {
|
||||
if (mediaTypes) {
|
||||
// 检查文件大小限制
|
||||
if (isFileSizeExceeded(filePath)) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute,
|
||||
"视频文件大小超过" + ConfigConstants.getMediaConvertMaxSize() + "MB限制,禁止转换");
|
||||
}
|
||||
|
||||
// 使用改进的转换方法
|
||||
String convertedPath = convertVideoWithImprovedTimeout(filePath, outFilePath, fileAttribute);
|
||||
if (convertedPath != null) {
|
||||
model.addAttribute("mediaUrl", fileHandlerService.getRelativePath(convertedPath));
|
||||
|
||||
// 缓存转换结果
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(convertedPath));
|
||||
}
|
||||
return MEDIA_FILE_PREVIEW_PAGE;
|
||||
} else {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "视频转换失败,请联系管理员");
|
||||
}
|
||||
} else {
|
||||
// 不需要转换的文件
|
||||
model.addAttribute("mediaUrl", fileHandlerService.getRelativePath(outFilePath));
|
||||
return MEDIA_FILE_PREVIEW_PAGE;
|
||||
if (mediaTypes) {
|
||||
// 检查文件大小限制
|
||||
if (isFileSizeExceeded(filePath)) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute,
|
||||
"视频文件大小超过" + ConfigConstants.getMediaConvertMaxSize() + "MB限制,禁止转换");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("处理媒体文件失败: {}", filePath, e);
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute,
|
||||
"视频处理异常: " + getErrorMessage(e));
|
||||
try {
|
||||
// 启动异步转换,并添加回调处理
|
||||
startAsyncConversion(filePath, outFilePath, cacheName, fileAttribute);
|
||||
// 返回等待页面
|
||||
model.addAttribute("fileName", fileName);
|
||||
model.addAttribute("message", "视频文件正在转换中,请稍候...");
|
||||
return WAITING_FILE_PREVIEW_PAGE;
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to start video conversion: {}", filePath, e);
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "视频转换异常,请联系管理员");
|
||||
}
|
||||
} else {
|
||||
// 不需要转换的文件,直接返回
|
||||
model.addAttribute("mediaUrl", fileHandlerService.getRelativePath(outFilePath));
|
||||
return MEDIA_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
}
|
||||
|
||||
// HTTP协议的媒体文件,直接播放
|
||||
if (type.equals(FileType.MEDIA)) {
|
||||
model.addAttribute("mediaUrl", url);
|
||||
@@ -118,6 +120,45 @@ public class MediaFilePreviewImpl implements FilePreview {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "系统还不支持该格式文件的在线预览");
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动异步转换,并在转换完成后处理后续操作
|
||||
*/
|
||||
private void startAsyncConversion(String filePath, String outFilePath,
|
||||
String cacheName, FileAttribute fileAttribute) {
|
||||
// 启动异步转换
|
||||
CompletableFuture<Boolean> conversionFuture = mediatomp4Service.convertToMp4Async(
|
||||
filePath,
|
||||
outFilePath,
|
||||
cacheName,
|
||||
fileAttribute
|
||||
);
|
||||
|
||||
// 添加转换完成后的回调
|
||||
conversionFuture.whenCompleteAsync((success, throwable) -> {
|
||||
if (success != null && success) {
|
||||
try {
|
||||
// 1. 是否保留源文件(只在转换成功后才删除)
|
||||
if (!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) {
|
||||
KkFileUtils.deleteFileByPath(filePath);
|
||||
}
|
||||
// 2. 加入视频缓存(只在转换成功后才添加)
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
fileHandlerService.addConvertedMedias(cacheName,
|
||||
fileHandlerService.getRelativePath(outFilePath));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("视频转换后续处理失败: {}", filePath, e);
|
||||
}
|
||||
} else {
|
||||
// 转换失败,保留源文件供排查问题
|
||||
logger.error("视频转换失败,保留源文件: {}", filePath);
|
||||
if (throwable != null) {
|
||||
logger.error("视频转换失败原因: ", throwable);
|
||||
}
|
||||
}
|
||||
}, callbackExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查文件大小是否超过限制
|
||||
*/
|
||||
@@ -139,99 +180,14 @@ public class MediaFilePreviewImpl implements FilePreview {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 改进的转换方法
|
||||
*/
|
||||
private String convertVideoWithImprovedTimeout(String filePath, String outFilePath,
|
||||
FileAttribute fileAttribute) {
|
||||
try {
|
||||
// 检查文件是否存在
|
||||
File outputFile = new File(outFilePath);
|
||||
if (outputFile.exists() && !fileAttribute.forceUpdatedCache()) {
|
||||
logger.info("输出文件已存在且非强制更新模式,跳过转换!");
|
||||
return outFilePath;
|
||||
}
|
||||
|
||||
// 使用改进的异步转换方法
|
||||
CompletableFuture<Boolean> future =
|
||||
Mediatomp4Service.convertToMp4Async(filePath, outFilePath, fileAttribute);
|
||||
|
||||
// 计算超时时间
|
||||
File inputFile = new File(filePath);
|
||||
long fileSizeMB = inputFile.length() / (1024 * 1024);
|
||||
int timeoutSeconds = calculateTimeout(fileSizeMB);
|
||||
|
||||
try {
|
||||
boolean result = future.get(timeoutSeconds, TimeUnit.SECONDS);
|
||||
if (result) {
|
||||
// 验证输出文件
|
||||
File convertedFile = new File(outFilePath);
|
||||
if (!convertedFile.exists() || convertedFile.length() == 0) {
|
||||
throw new IOException("转换完成但输出文件无效");
|
||||
}
|
||||
return outFilePath;
|
||||
} else {
|
||||
throw new Exception("转换返回失败状态");
|
||||
}
|
||||
} catch (TimeoutException e) {
|
||||
// 超时后尝试获取任务ID并取消
|
||||
logger.error("视频转换超时: {}, 文件大小: {}MB, 超时: {}秒",
|
||||
filePath, fileSizeMB, timeoutSeconds);
|
||||
|
||||
throw new RuntimeException("视频转换超时,文件可能过大");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("视频转换异常: {}", filePath, e);
|
||||
throw new RuntimeException("视频转换失败: " + getErrorMessage(e), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算超时时间 - 从配置文件读取
|
||||
*/
|
||||
public int calculateTimeout(long fileSizeMB) {
|
||||
// 如果超时功能被禁用,返回一个非常大的值
|
||||
if (!ConfigConstants.isMediaTimeoutEnabled()) {
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
|
||||
// 根据文件大小从配置文件读取超时时间
|
||||
if (fileSizeMB < 10) return ConfigConstants.getMediaSmallFileTimeout(); // 小文件
|
||||
if (fileSizeMB < 50) return ConfigConstants.getMediaMediumFileTimeout(); // 中等文件
|
||||
if (fileSizeMB < 200) return ConfigConstants.getMediaLargeFileTimeout(); // 较大文件
|
||||
if (fileSizeMB < 500) return ConfigConstants.getMediaXLFileTimeout(); // 大文件
|
||||
if (fileSizeMB < 1024) return ConfigConstants.getMediaXXLFileTimeout(); // 超大文件
|
||||
return ConfigConstants.getMediaXXXLFileTimeout(); // 极大文件
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否需要转换
|
||||
*/
|
||||
private boolean checkNeedConvert(boolean mediaTypes) {
|
||||
// 1.检查开关是否开启
|
||||
// 检查转换开关是否开启
|
||||
if ("true".equals(ConfigConstants.getMediaConvertDisable())) {
|
||||
return mediaTypes;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取友好的错误信息
|
||||
*/
|
||||
private String getErrorMessage(Exception e) {
|
||||
if (e instanceof CancellationException) {
|
||||
return "转换被取消";
|
||||
} else if (e instanceof TimeoutException) {
|
||||
return "转换超时";
|
||||
} else if (e.getMessage() != null) {
|
||||
// 截取主要错误信息
|
||||
String msg = e.getMessage();
|
||||
if (msg.length() > 100) {
|
||||
msg = msg.substring(0, 100) + "...";
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
return "未知错误";
|
||||
}
|
||||
}
|
||||
@@ -8,19 +8,23 @@ import cn.keking.service.FilePreview;
|
||||
import cn.keking.service.OfficeToPdfService;
|
||||
import cn.keking.service.PdfToJpgService;
|
||||
import cn.keking.utils.DownloadUtils;
|
||||
import cn.keking.utils.FileConvertStatusManager;
|
||||
import cn.keking.utils.KkFileUtils;
|
||||
import cn.keking.utils.OfficeUtils;
|
||||
import cn.keking.utils.WebUtils;
|
||||
import cn.keking.web.filter.BaseUrlFilter;
|
||||
import org.apache.commons.lang3.exception.ExceptionUtils;
|
||||
import org.apache.poi.EncryptedDocumentException;
|
||||
import org.jodconverter.core.office.OfficeException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* Created by kl on 2018/1/17.
|
||||
@@ -29,9 +33,12 @@ import java.util.List;
|
||||
@Service
|
||||
public class OfficeFilePreviewImpl implements FilePreview {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(OfficeFilePreviewImpl.class);
|
||||
public static final String OFFICE_PREVIEW_TYPE_IMAGE = "image";
|
||||
public static final String OFFICE_PREVIEW_TYPE_ALL_IMAGES = "allImages";
|
||||
private static final String OFFICE_PASSWORD_MSG = "password";
|
||||
|
||||
// 用于处理回调的线程池
|
||||
private static final ExecutorService callbackExecutor = Executors.newFixedThreadPool(3);
|
||||
|
||||
private final FileHandlerService fileHandlerService;
|
||||
private final OfficeToPdfService officeToPdfService;
|
||||
@@ -54,12 +61,16 @@ public class OfficeFilePreviewImpl implements FilePreview {
|
||||
String suffix = fileAttribute.getSuffix(); //获取文件后缀
|
||||
String fileName = fileAttribute.getName(); //获取文件原始名称
|
||||
String filePassword = fileAttribute.getFilePassword(); //获取密码
|
||||
boolean forceUpdatedCache=fileAttribute.forceUpdatedCache(); //是否启用强制更新命令
|
||||
boolean forceUpdatedCache = fileAttribute.forceUpdatedCache(); //是否启用强制更新命令
|
||||
boolean isHtmlView = fileAttribute.isHtmlView(); //xlsx 转换成html
|
||||
String cacheName = fileAttribute.getCacheName(); //转换后的文件名
|
||||
String outFilePath = fileAttribute.getOutFilePath(); //转换后生成文件的路径
|
||||
|
||||
// 查询转换状态
|
||||
checkAndHandleConvertStatus(model, fileName, cacheName,fileAttribute);
|
||||
|
||||
if (!officePreviewType.equalsIgnoreCase("html")) {
|
||||
if (ConfigConstants.getOfficeTypeWeb() .equalsIgnoreCase("web")) {
|
||||
if (ConfigConstants.getOfficeTypeWeb().equalsIgnoreCase("web")) {
|
||||
if (suffix.equalsIgnoreCase("xlsx")) {
|
||||
model.addAttribute("pdfUrl", KkFileUtils.htmlEscape(url)); //特殊符号处理
|
||||
return XLSX_FILE_PREVIEW_PAGE;
|
||||
@@ -70,14 +81,190 @@ public class OfficeFilePreviewImpl implements FilePreview {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (forceUpdatedCache|| !fileHandlerService.listConvertedFiles().containsKey(cacheName) || !ConfigConstants.isCacheEnabled()) {
|
||||
// 下载远程文件到本地,如果文件在本地已存在不会重复下载
|
||||
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName);
|
||||
if (response.isFailure()) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg());
|
||||
|
||||
// 图片预览模式(异步转换)
|
||||
if (!isHtmlView && baseUrl != null && (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType))) {
|
||||
boolean jiami = false;
|
||||
if (!ObjectUtils.isEmpty(filePassword)) {
|
||||
jiami = pdftojpgservice.hasEncryptedPdfCacheSimple(outFilePath);
|
||||
}
|
||||
if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(cacheName) || !ConfigConstants.isCacheEnabled()) {
|
||||
if (jiami) {
|
||||
return getPreviewType(model, fileAttribute, officePreviewType, cacheName, outFilePath);
|
||||
}
|
||||
// 下载文件
|
||||
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName);
|
||||
if (response.isFailure()) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg());
|
||||
}
|
||||
String filePath = response.getContent();
|
||||
|
||||
// 检查是否加密文件
|
||||
boolean isPwdProtectedOffice = OfficeUtils.isPwdProtected(filePath);
|
||||
if (isPwdProtectedOffice && !StringUtils.hasLength(filePassword)) {
|
||||
// 加密文件需要密码
|
||||
model.addAttribute("needFilePassword", true);
|
||||
model.addAttribute("fileName", fileName);
|
||||
model.addAttribute("cacheName", cacheName);
|
||||
return EXEL_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
|
||||
try {
|
||||
// 启动异步转换
|
||||
startAsyncOfficeConversion(filePath, outFilePath, cacheName, fileAttribute, officePreviewType);
|
||||
// 返回等待页面
|
||||
model.addAttribute("fileName", fileName);
|
||||
model.addAttribute("message", "文件正在转换中,请稍候...");
|
||||
return WAITING_FILE_PREVIEW_PAGE;
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to start Office conversion: {}", filePath, e);
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "文件转换异常,请联系管理员");
|
||||
}
|
||||
} else {
|
||||
// 如果已有缓存,直接渲染预览
|
||||
return getPreviewType(model, fileAttribute, officePreviewType, cacheName, outFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
// 处理普通Office转PDF预览
|
||||
return handleRegularOfficePreview(model, fileAttribute, fileName, forceUpdatedCache, cacheName, outFilePath,
|
||||
isHtmlView, userToken, filePassword);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动异步Office转换
|
||||
*/
|
||||
private void startAsyncOfficeConversion(String filePath, String outFilePath, String cacheName,
|
||||
FileAttribute fileAttribute,
|
||||
String officePreviewType) {
|
||||
// 启动异步转换
|
||||
CompletableFuture<List<String>> conversionFuture = CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
// 更新状态
|
||||
FileConvertStatusManager.startConvert(cacheName);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在启动Office转换", 20);
|
||||
|
||||
// 转换Office到PDF
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在转换Office到jpg", 60);
|
||||
officeToPdfService.openOfficeToPDF(filePath, outFilePath, fileAttribute);
|
||||
|
||||
|
||||
if (fileAttribute.isHtmlView()) {
|
||||
// 对转换后的文件进行操作(改变编码方式)
|
||||
FileConvertStatusManager.updateProgress(cacheName, "处理HTML编码", 95);
|
||||
fileHandlerService.doActionConvertedFile(outFilePath);
|
||||
}
|
||||
|
||||
// 是否需要转换为图片
|
||||
List<String> imageUrls = null;
|
||||
if (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) ||
|
||||
OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType)) {
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在转换PDF为图片", 90);
|
||||
imageUrls = pdftojpgservice.pdf2jpg(outFilePath, outFilePath, cacheName, fileAttribute);
|
||||
}
|
||||
|
||||
// 缓存处理
|
||||
boolean isPwdProtectedOffice = OfficeUtils.isPwdProtected(filePath);
|
||||
boolean userToken = fileAttribute.getUsePasswordCache();
|
||||
String filePassword = fileAttribute.getFilePassword();
|
||||
|
||||
if (ConfigConstants.isCacheEnabled() && (ObjectUtils.isEmpty(filePassword) || userToken || !isPwdProtectedOffice)) {
|
||||
fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath));
|
||||
}
|
||||
|
||||
FileConvertStatusManager.updateProgress(cacheName, "转换完成", 100);
|
||||
FileConvertStatusManager.convertSuccess(cacheName);
|
||||
|
||||
return imageUrls;
|
||||
} catch (OfficeException e) {
|
||||
boolean isPwdProtectedOffice = OfficeUtils.isPwdProtected(filePath);
|
||||
String filePassword = fileAttribute.getFilePassword();
|
||||
if (isPwdProtectedOffice && !OfficeUtils.isCompatible(filePath, filePassword)) {
|
||||
FileConvertStatusManager.markError(cacheName, "文件密码错误,请重新输入");
|
||||
} else {
|
||||
logger.error("Office转换执行失败: {}", cacheName, e);
|
||||
FileConvertStatusManager.markError(cacheName, "Office转换失败: " + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
logger.error("Office转换执行失败: {}", cacheName, e);
|
||||
|
||||
// 检查是否已经标记为超时
|
||||
FileConvertStatusManager.ConvertStatus status = FileConvertStatusManager.getConvertStatus(cacheName);
|
||||
if (status == null || status.getStatus() != FileConvertStatusManager.Status.TIMEOUT) {
|
||||
FileConvertStatusManager.markError(cacheName, "转换失败: " + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
// 添加转换完成后的回调
|
||||
conversionFuture.thenAcceptAsync(imageUrls -> {
|
||||
try {
|
||||
// 这里假设imageUrls不为null且不为空表示转换成功
|
||||
if (imageUrls != null && !imageUrls.isEmpty()) {
|
||||
// 是否保留源文件(只在转换成功后才删除)
|
||||
if (!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) {
|
||||
KkFileUtils.deleteFileByPath(filePath);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Office转换后续处理失败: {}", filePath, e);
|
||||
}
|
||||
}, callbackExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取预览类型(图片预览)
|
||||
*/
|
||||
String getPreviewType(Model model, FileAttribute fileAttribute, String officePreviewType,
|
||||
String cacheName, String outFilePath) {
|
||||
String suffix = fileAttribute.getSuffix();
|
||||
boolean isPPT = suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx");
|
||||
List<String> imageUrls;
|
||||
|
||||
try {
|
||||
if (pdftojpgservice.hasEncryptedPdfCacheSimple(outFilePath)) {
|
||||
imageUrls = pdftojpgservice.getEncryptedPdfCache(outFilePath);
|
||||
} else {
|
||||
imageUrls = fileHandlerService.loadPdf2jpgCache(outFilePath);
|
||||
}
|
||||
|
||||
if (imageUrls == null || imageUrls.isEmpty()) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "Office转换缓存异常,请联系管理员");
|
||||
}
|
||||
|
||||
model.addAttribute("imgUrls", imageUrls);
|
||||
model.addAttribute("currentUrl", imageUrls.getFirst());
|
||||
|
||||
if (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType)) {
|
||||
// PPT 图片模式使用专用预览页面
|
||||
return (isPPT ? PPT_FILE_PREVIEW_PAGE : OFFICE_PICTURE_FILE_PREVIEW_PAGE);
|
||||
} else {
|
||||
return PICTURE_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("渲染Office预览页面失败: {}", cacheName, e);
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "渲染预览页面异常,请联系管理员");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理普通Office预览(转PDF)
|
||||
*/
|
||||
private String handleRegularOfficePreview(Model model, FileAttribute fileAttribute,
|
||||
String fileName, boolean forceUpdatedCache, String cacheName,
|
||||
String outFilePath, boolean isHtmlView, boolean userToken,
|
||||
String filePassword) {
|
||||
|
||||
if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(cacheName) || !ConfigConstants.isCacheEnabled()) {
|
||||
// 下载远程文件到本地,如果文件在本地已存在不会重复下载
|
||||
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName);
|
||||
if (response.isFailure()) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg());
|
||||
}
|
||||
String filePath = response.getContent();
|
||||
boolean isPwdProtectedOffice = OfficeUtils.isPwdProtected(filePath); // 判断是否加密文件
|
||||
|
||||
boolean isPwdProtectedOffice = OfficeUtils.isPwdProtected(filePath); // 判断是否加密文件
|
||||
if (isPwdProtectedOffice && !StringUtils.hasLength(filePassword)) {
|
||||
// 加密文件需要密码
|
||||
model.addAttribute("needFilePassword", true);
|
||||
@@ -109,43 +296,33 @@ public class OfficeFilePreviewImpl implements FilePreview {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if (!isHtmlView && baseUrl != null && (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType))) {
|
||||
return getPreviewType(model, fileAttribute, officePreviewType, cacheName, outFilePath, fileHandlerService, OFFICE_PREVIEW_TYPE_IMAGE, otherFilePreview);
|
||||
}
|
||||
model.addAttribute("pdfUrl", WebUtils.encodeFileName(cacheName)); //输出转义文件名 方便url识别
|
||||
return isHtmlView ? EXEL_FILE_PREVIEW_PAGE : PDF_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
|
||||
String getPreviewType(Model model, FileAttribute fileAttribute, String officePreviewType, String pdfName, String outFilePath, FileHandlerService fileHandlerService, String officePreviewTypeImage, OtherFilePreviewImpl otherFilePreview) {
|
||||
String suffix = fileAttribute.getSuffix();
|
||||
boolean isPPT = suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx");
|
||||
List<String> imageUrls = null;
|
||||
try {
|
||||
imageUrls = pdftojpgservice.pdf2jpg(outFilePath,outFilePath, pdfName, fileAttribute);
|
||||
} catch (Exception e) {
|
||||
Throwable[] throwableArray = ExceptionUtils.getThrowables(e);
|
||||
for (Throwable throwable : throwableArray) {
|
||||
if (throwable instanceof IOException || throwable instanceof EncryptedDocumentException) {
|
||||
if (e.getMessage().toLowerCase().contains(OFFICE_PASSWORD_MSG)) {
|
||||
model.addAttribute("needFilePassword", true);
|
||||
return EXEL_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 异步方法
|
||||
*/
|
||||
public String checkAndHandleConvertStatus(Model model, String fileName, String cacheName, FileAttribute fileAttribute){
|
||||
FileConvertStatusManager.ConvertStatus status = FileConvertStatusManager.getConvertStatus(cacheName);
|
||||
int refreshSchedule = ConfigConstants.getTime();
|
||||
if (status != null) {
|
||||
if (status.getStatus() == FileConvertStatusManager.Status.CONVERTING) {
|
||||
// 正在转换中,返回等待页面
|
||||
model.addAttribute("fileName", fileName);
|
||||
model.addAttribute("time", refreshSchedule);
|
||||
model.addAttribute("message", status.getRealTimeMessage());
|
||||
return WAITING_FILE_PREVIEW_PAGE;
|
||||
} else if (status.getStatus() == FileConvertStatusManager.Status.TIMEOUT) {
|
||||
// 超时状态,不允许重新转换
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "文件转换已超时,无法继续转换");
|
||||
} else if (status.getStatus() == FileConvertStatusManager.Status.FAILED) {
|
||||
// 失败状态,不允许重新转换
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "文件转换失败,无法继续转换");
|
||||
}
|
||||
}
|
||||
if (imageUrls == null || imageUrls.size() < 1) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "office转图片异常,请联系管理员");
|
||||
}
|
||||
model.addAttribute("imgUrls", imageUrls);
|
||||
model.addAttribute("currentUrl", imageUrls.get(0));
|
||||
if (officePreviewTypeImage.equals(officePreviewType)) {
|
||||
// PPT 图片模式使用专用预览页面
|
||||
return (isPPT ? PPT_FILE_PREVIEW_PAGE : OFFICE_PICTURE_FILE_PREVIEW_PAGE);
|
||||
} else {
|
||||
return PICTURE_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -7,14 +7,23 @@ import cn.keking.service.FileHandlerService;
|
||||
import cn.keking.service.FilePreview;
|
||||
import cn.keking.service.PdfToJpgService;
|
||||
import cn.keking.utils.DownloadUtils;
|
||||
import cn.keking.utils.FileConvertStatusManager;
|
||||
import cn.keking.utils.KkFileUtils;
|
||||
import cn.keking.utils.WebUtils;
|
||||
import org.apache.commons.lang3.exception.ExceptionUtils;
|
||||
import org.apache.poi.EncryptedDocumentException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* Created by kl on 2018/1/17.
|
||||
@@ -23,80 +32,263 @@ import java.util.List;
|
||||
@Service
|
||||
public class PdfFilePreviewImpl implements FilePreview {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PdfFilePreviewImpl.class);
|
||||
private static final String PDF_PASSWORD_MSG = "password";
|
||||
private final FileHandlerService fileHandlerService;
|
||||
private final OtherFilePreviewImpl otherFilePreview;
|
||||
private final PdfToJpgService pdftojpgservice;
|
||||
private static final String PDF_PASSWORD_MSG = "password";
|
||||
public PdfFilePreviewImpl(FileHandlerService fileHandlerService, OtherFilePreviewImpl otherFilePreview, PdfToJpgService pdftojpgservice) {
|
||||
|
||||
// 用于处理回调的线程池
|
||||
private static final ExecutorService callbackExecutor = Executors.newFixedThreadPool(3);
|
||||
|
||||
public PdfFilePreviewImpl(FileHandlerService fileHandlerService,
|
||||
OtherFilePreviewImpl otherFilePreview,
|
||||
PdfToJpgService pdftojpgservice) {
|
||||
this.fileHandlerService = fileHandlerService;
|
||||
this.otherFilePreview = otherFilePreview;
|
||||
this.pdftojpgservice = pdftojpgservice;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
String pdfName = fileAttribute.getName(); //获取原始文件名
|
||||
String officePreviewType = fileAttribute.getOfficePreviewType(); //转换类型
|
||||
boolean forceUpdatedCache=fileAttribute.forceUpdatedCache(); //是否启用强制更新命令
|
||||
boolean forceUpdatedCache = fileAttribute.forceUpdatedCache(); //是否启用强制更新命令
|
||||
String outFilePath = fileAttribute.getOutFilePath(); //生成的文件路径
|
||||
String originFilePath = fileAttribute.getOriginFilePath(); //原始文件路径
|
||||
if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType)) {
|
||||
//当文件不存在时,就去下载
|
||||
if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) {
|
||||
String originFilePath; //原始文件路径
|
||||
String cacheName = fileAttribute.getCacheName();
|
||||
String filePassword = fileAttribute.getFilePassword(); // 获取密码
|
||||
int refreshSchedule = ConfigConstants.getTime();
|
||||
// 查询转换状态
|
||||
FileConvertStatusManager.ConvertStatus status = FileConvertStatusManager.getConvertStatus(cacheName);
|
||||
if (status != null) {
|
||||
if (status.getStatus() == FileConvertStatusManager.Status.CONVERTING) {
|
||||
// 正在转换中,返回等待页面
|
||||
model.addAttribute("fileName", pdfName);
|
||||
model.addAttribute("time", refreshSchedule);
|
||||
model.addAttribute("message", status.getRealTimeMessage());
|
||||
return WAITING_FILE_PREVIEW_PAGE;
|
||||
} else if (status.getStatus() == FileConvertStatusManager.Status.TIMEOUT) {
|
||||
// 超时状态,不允许重新转换
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "文件转换已超时,无法继续转换");
|
||||
}
|
||||
}
|
||||
boolean jiami=false;
|
||||
if(!ObjectUtils.isEmpty(filePassword)){
|
||||
jiami=pdftojpgservice.hasEncryptedPdfCacheSimple(outFilePath);
|
||||
}
|
||||
if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) ||
|
||||
OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType)) {
|
||||
|
||||
// 判断之前是否已转换过,如果转换过,直接返回,否则执行转换
|
||||
if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(cacheName) || !ConfigConstants.isCacheEnabled()) {
|
||||
if(jiami){
|
||||
return renderPreview(model, cacheName, outFilePath,
|
||||
officePreviewType, pdfName, fileAttribute);
|
||||
}
|
||||
// 当文件不存在时,就去下载
|
||||
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, pdfName);
|
||||
if (response.isFailure()) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg());
|
||||
}
|
||||
originFilePath = response.getContent();
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
// 加入缓存
|
||||
fileHandlerService.addConvertedFile(pdfName, fileHandlerService.getRelativePath(originFilePath));
|
||||
// 检查文件是否需要密码,但不启动转换
|
||||
if (filePassword == null || filePassword.trim().isEmpty()) {
|
||||
// 没有提供密码,先检查文件是否需要密码
|
||||
if (checkIfPdfNeedsPassword(originFilePath, cacheName, pdfName)) {
|
||||
model.addAttribute("needFilePassword", true);
|
||||
model.addAttribute("fileName", pdfName);
|
||||
model.addAttribute("cacheName", cacheName);
|
||||
return EXEL_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
}
|
||||
try {
|
||||
// 启动异步转换
|
||||
startAsyncPdfConversion(originFilePath, outFilePath, cacheName, pdfName, fileAttribute);
|
||||
// 返回等待页面
|
||||
model.addAttribute("fileName", pdfName);
|
||||
model.addAttribute("message", "文件正在转换中,请稍候...");
|
||||
return WAITING_FILE_PREVIEW_PAGE;
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to start PDF conversion: {}", originFilePath, e);
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "PDF转换异常,请联系管理员");
|
||||
}
|
||||
} else {
|
||||
// 如果已有缓存,直接渲染预览
|
||||
return renderPreview(model, cacheName, outFilePath,
|
||||
officePreviewType, pdfName, fileAttribute);
|
||||
}
|
||||
List<String> imageUrls;
|
||||
try {
|
||||
imageUrls = pdftojpgservice.pdf2jpg(originFilePath,outFilePath, pdfName, fileAttribute);
|
||||
} else {
|
||||
// 处理普通PDF预览(非图片转换)
|
||||
return handleRegularPdfPreview(url, model, fileAttribute, pdfName, forceUpdatedCache, outFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查PDF文件是否需要密码(不进行实际转换)
|
||||
*/
|
||||
private boolean checkIfPdfNeedsPassword(String originFilePath, String cacheName, String pdfName) {
|
||||
try {
|
||||
// 尝试用空密码加载PDF,检查是否需要密码
|
||||
File pdfFile = new File(originFilePath);
|
||||
if (!pdfFile.exists()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 使用try-with-resources确保资源释放
|
||||
try (org.apache.pdfbox.pdmodel.PDDocument tempDoc = org.apache.pdfbox.Loader.loadPDF(pdfFile, "")) {
|
||||
// 如果能加载成功,说明不需要密码
|
||||
int pageCount = tempDoc.getNumberOfPages();
|
||||
logger.info("PDF文件不需要密码,总页数: {},文件: {}", pageCount, originFilePath);
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
Throwable[] throwableArray = ExceptionUtils.getThrowables(e);
|
||||
for (Throwable throwable : throwableArray) {
|
||||
if (throwable instanceof IOException || throwable instanceof EncryptedDocumentException) {
|
||||
if (e.getMessage().toLowerCase().contains(PDF_PASSWORD_MSG)) {
|
||||
model.addAttribute("needFilePassword", true);
|
||||
return EXEL_FILE_PREVIEW_PAGE;
|
||||
FileConvertStatusManager.convertSuccess(cacheName);
|
||||
logger.info("PDF文件需要密码: {}", originFilePath);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "pdf转图片异常,请联系管理员");
|
||||
logger.warn("PDF文件检查异常: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
if (imageUrls == null || imageUrls.size() < 1) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "pdf转图片异常,请联系管理员");
|
||||
} catch (Exception e) {
|
||||
logger.error("检查PDF密码状态失败: {}", originFilePath, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动异步PDF转换
|
||||
*/
|
||||
private void startAsyncPdfConversion(String originFilePath, String outFilePath,
|
||||
String cacheName, String pdfName,
|
||||
FileAttribute fileAttribute) {
|
||||
// 启动异步转换
|
||||
CompletableFuture<List<String>> conversionFuture = CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
// 更新状态
|
||||
FileConvertStatusManager.startConvert(cacheName);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在启动PDF转换", 10);
|
||||
|
||||
List<String> imageUrls = pdftojpgservice.pdf2jpg(originFilePath, outFilePath,
|
||||
pdfName, fileAttribute);
|
||||
|
||||
if (imageUrls != null && !imageUrls.isEmpty()) {
|
||||
boolean usePasswordCache = fileAttribute.getUsePasswordCache();
|
||||
String filePassword = fileAttribute.getFilePassword();
|
||||
if (ConfigConstants.isCacheEnabled() && (ObjectUtils.isEmpty(filePassword) || usePasswordCache)) {
|
||||
fileHandlerService.addConvertedFile(pdfName, fileHandlerService.getRelativePath(outFilePath));
|
||||
}
|
||||
FileConvertStatusManager.updateProgress(cacheName, "转换完成", 100);
|
||||
// 短暂延迟后清理状态
|
||||
FileConvertStatusManager.convertSuccess(cacheName);
|
||||
return imageUrls;
|
||||
} else {
|
||||
FileConvertStatusManager.markError(cacheName, "PDF转换失败,未生成图片");
|
||||
return null;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Throwable[] throwableArray = ExceptionUtils.getThrowables(e);
|
||||
for (Throwable throwable : throwableArray) {
|
||||
if (throwable instanceof IOException || throwable instanceof EncryptedDocumentException) {
|
||||
if (e.getMessage().toLowerCase().contains(PDF_PASSWORD_MSG)) {
|
||||
// 标记为需要密码的状态
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.error("PDF转换执行失败: {}", cacheName, e);
|
||||
|
||||
// 检查是否已经标记为超时
|
||||
FileConvertStatusManager.ConvertStatus status = FileConvertStatusManager.getConvertStatus(cacheName);
|
||||
if (status == null || status.getStatus() != FileConvertStatusManager.Status.TIMEOUT) {
|
||||
FileConvertStatusManager.markError(cacheName, "转换失败: " + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
// 添加转换完成后的回调
|
||||
conversionFuture.whenCompleteAsync((imageUrls, throwable) -> {
|
||||
if (imageUrls != null && !imageUrls.isEmpty()) {
|
||||
try {
|
||||
// 是否保留PDF源文件(只在转换成功后才删除)
|
||||
if (!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) {
|
||||
KkFileUtils.deleteFileByPath(originFilePath);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("PDF转换后续处理失败: {}", originFilePath, e);
|
||||
}
|
||||
} else {
|
||||
// 转换失败,保留源文件供排查问题
|
||||
logger.error("PDF转换失败,保留源文件: {}", originFilePath);
|
||||
if (throwable != null) {
|
||||
logger.error("转换失败原因: ", throwable);
|
||||
}
|
||||
}
|
||||
}, callbackExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染预览页面
|
||||
*/
|
||||
private String renderPreview(Model model, String cacheName,
|
||||
String outFilePath, String officePreviewType,
|
||||
String pdfName, FileAttribute fileAttribute) {
|
||||
try {
|
||||
List<String> imageUrls;
|
||||
if(pdftojpgservice.hasEncryptedPdfCacheSimple(outFilePath)){
|
||||
imageUrls = pdftojpgservice.getEncryptedPdfCache(outFilePath);
|
||||
}else {
|
||||
imageUrls = fileHandlerService.loadPdf2jpgCache(outFilePath);
|
||||
}
|
||||
if (imageUrls == null || imageUrls.isEmpty()) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "PDF转换缓存异常,请联系管理员");
|
||||
}
|
||||
|
||||
model.addAttribute("imgUrls", imageUrls);
|
||||
model.addAttribute("currentUrl", imageUrls.get(0));
|
||||
|
||||
if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType)) {
|
||||
return OFFICE_PICTURE_FILE_PREVIEW_PAGE;
|
||||
} else {
|
||||
return PICTURE_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
} else {
|
||||
// 不是http开头,浏览器不能直接访问,需下载到本地
|
||||
if (url != null && !url.toLowerCase().startsWith("http")) {
|
||||
if (!fileHandlerService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) {
|
||||
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, pdfName);
|
||||
if (response.isFailure()) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg());
|
||||
}
|
||||
model.addAttribute("pdfUrl", fileHandlerService.getRelativePath(response.getContent()));
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
// 加入缓存
|
||||
fileHandlerService.addConvertedFile(pdfName, fileHandlerService.getRelativePath(outFilePath));
|
||||
}
|
||||
} else {
|
||||
model.addAttribute("pdfUrl", WebUtils.encodeFileName(pdfName));
|
||||
} catch (Exception e) {
|
||||
logger.error("渲染PDF预览页面失败: {}", cacheName, e);
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "渲染预览页面异常,请联系管理员");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理普通PDF预览(非图片转换)
|
||||
*/
|
||||
private String handleRegularPdfPreview(String url, Model model, FileAttribute fileAttribute,
|
||||
String pdfName, boolean forceUpdatedCache,
|
||||
String outFilePath) {
|
||||
// 不是http开头,浏览器不能直接访问,需下载到本地
|
||||
if (url != null && !url.toLowerCase().startsWith("http")) {
|
||||
if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) {
|
||||
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, pdfName);
|
||||
if (response.isFailure()) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg());
|
||||
}
|
||||
model.addAttribute("pdfUrl", fileHandlerService.getRelativePath(response.getContent()));
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
// 加入缓存
|
||||
fileHandlerService.addConvertedFile(pdfName, fileHandlerService.getRelativePath(outFilePath));
|
||||
}
|
||||
} else {
|
||||
model.addAttribute("pdfUrl", url);
|
||||
model.addAttribute("pdfUrl", WebUtils.encodeFileName(pdfName));
|
||||
}
|
||||
} else {
|
||||
model.addAttribute("pdfUrl", url);
|
||||
}
|
||||
return PDF_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -77,7 +77,7 @@ public class SimTextFilePreviewImpl implements FilePreview {
|
||||
return null;
|
||||
}
|
||||
if (!file.exists() || file.length() == 0) {
|
||||
return "";
|
||||
return "KK提醒您:文件不存在或者已经被删除了!";
|
||||
} else {
|
||||
String charset = EncodingDetects.getJavaEncode(filePath);
|
||||
if ("ASCII".equals(charset)) {
|
||||
|
||||
@@ -7,12 +7,18 @@ import cn.keking.service.FileHandlerService;
|
||||
import cn.keking.service.FilePreview;
|
||||
import cn.keking.service.TifToPdfService;
|
||||
import cn.keking.utils.DownloadUtils;
|
||||
import cn.keking.utils.FileConvertStatusManager;
|
||||
import cn.keking.utils.KkFileUtils;
|
||||
import cn.keking.utils.WebUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* tiff 图片文件处理
|
||||
@@ -22,21 +28,37 @@ import java.util.List;
|
||||
@Service
|
||||
public class TiffFilePreviewImpl implements FilePreview {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(TiffFilePreviewImpl.class);
|
||||
|
||||
// 用于处理回调的线程池
|
||||
private static final ExecutorService callbackExecutor = Executors.newFixedThreadPool(3);
|
||||
|
||||
private final FileHandlerService fileHandlerService;
|
||||
private final OtherFilePreviewImpl otherFilePreview;
|
||||
private final TifToPdfService tiftoservice;
|
||||
public TiffFilePreviewImpl(FileHandlerService fileHandlerService,OtherFilePreviewImpl otherFilePreview,TifToPdfService tiftoservice) {
|
||||
private final OfficeFilePreviewImpl officefilepreviewimpl;
|
||||
|
||||
public TiffFilePreviewImpl(FileHandlerService fileHandlerService, OtherFilePreviewImpl otherFilePreview, TifToPdfService tiftoservice, OfficeFilePreviewImpl officefilepreviewimpl) {
|
||||
this.fileHandlerService = fileHandlerService;
|
||||
this.otherFilePreview = otherFilePreview;
|
||||
this.tiftoservice = tiftoservice;
|
||||
this.officefilepreviewimpl = officefilepreviewimpl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
String fileName = fileAttribute.getName();
|
||||
String tifPreviewType = ConfigConstants.getTifPreviewType();
|
||||
String cacheName = fileAttribute.getCacheName();
|
||||
String cacheName = fileAttribute.getCacheName();
|
||||
String outFilePath = fileAttribute.getOutFilePath();
|
||||
boolean forceUpdatedCache=fileAttribute.forceUpdatedCache();
|
||||
boolean forceUpdatedCache = fileAttribute.forceUpdatedCache();
|
||||
|
||||
// 查询转换状态
|
||||
String statusResult = officefilepreviewimpl.checkAndHandleConvertStatus(model, fileName, cacheName, fileAttribute);
|
||||
if (statusResult != null) {
|
||||
return statusResult;
|
||||
}
|
||||
|
||||
if ("jpg".equalsIgnoreCase(tifPreviewType) || "pdf".equalsIgnoreCase(tifPreviewType)) {
|
||||
if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(cacheName) || !ConfigConstants.isCacheEnabled()) {
|
||||
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName);
|
||||
@@ -44,66 +66,111 @@ public class TiffFilePreviewImpl implements FilePreview {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg());
|
||||
}
|
||||
String filePath = response.getContent();
|
||||
|
||||
try {
|
||||
// 启动异步转换
|
||||
startAsyncTiffConversion(filePath, outFilePath, cacheName, fileName, fileAttribute, tifPreviewType, forceUpdatedCache);
|
||||
// 返回等待页面
|
||||
model.addAttribute("fileName", fileName);
|
||||
model.addAttribute("message", "文件正在转换中,请稍候...");
|
||||
return WAITING_FILE_PREVIEW_PAGE;
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to start TIF conversion: {}", filePath, e);
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "TIF转换异常,请联系系统管理员!");
|
||||
}
|
||||
} else {
|
||||
// 如果已有缓存,直接渲染预览
|
||||
if ("pdf".equalsIgnoreCase(tifPreviewType)) {
|
||||
try {
|
||||
tiftoservice.convertTif2Pdf(filePath, outFilePath,forceUpdatedCache);
|
||||
} catch (Exception e) {
|
||||
if (e.getMessage().contains("Bad endianness tag (not 0x4949 or 0x4d4d)") ) {
|
||||
model.addAttribute("imgUrls", url);
|
||||
model.addAttribute("currentUrl", url);
|
||||
return PICTURE_FILE_PREVIEW_PAGE;
|
||||
}else {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "TIF转pdf异常,请联系系统管理员!" );
|
||||
}
|
||||
}
|
||||
//是否保留TIFF源文件
|
||||
if (!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) {
|
||||
KkFileUtils.deleteFileByPath(filePath);
|
||||
}
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
// 加入缓存
|
||||
fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath));
|
||||
}
|
||||
model.addAttribute("pdfUrl", WebUtils.encodeFileName(cacheName));
|
||||
return PDF_FILE_PREVIEW_PAGE;
|
||||
}else {
|
||||
// 将tif转换为jpg,返回转换后的文件路径、文件名的list
|
||||
List<String> listPic2Jpg;
|
||||
try {
|
||||
listPic2Jpg = tiftoservice.convertTif2Jpg(filePath, outFilePath,forceUpdatedCache);
|
||||
} catch (Exception e) {
|
||||
if (e.getMessage().contains("Bad endianness tag (not 0x4949 or 0x4d4d)") ) {
|
||||
model.addAttribute("imgUrls", url);
|
||||
model.addAttribute("currentUrl", url);
|
||||
return PICTURE_FILE_PREVIEW_PAGE;
|
||||
}else {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "TIF转JPG异常,请联系系统管理员!" );
|
||||
}
|
||||
} else if ("jpg".equalsIgnoreCase(tifPreviewType)) {
|
||||
List<String> imgCache = fileHandlerService.getImgCache(cacheName);
|
||||
if (imgCache == null || imgCache.isEmpty()) {
|
||||
return otherFilePreview.notSupportedFile(model, fileAttribute, "TIF转换缓存异常,请联系系统管理员!");
|
||||
}
|
||||
//是否保留源文件,转换失败保留源文件,转换成功删除源文件
|
||||
if(!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) {
|
||||
KkFileUtils.deleteFileByPath(filePath);
|
||||
}
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
// 加入缓存
|
||||
fileHandlerService.putImgCache(cacheName, listPic2Jpg);
|
||||
fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath));
|
||||
}
|
||||
model.addAttribute("imgUrls", listPic2Jpg);
|
||||
model.addAttribute("currentUrl", listPic2Jpg.get(0));
|
||||
model.addAttribute("imgUrls", imgCache);
|
||||
model.addAttribute("currentUrl", imgCache.getFirst());
|
||||
return PICTURE_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
}
|
||||
if ("pdf".equalsIgnoreCase(tifPreviewType)) {
|
||||
model.addAttribute("pdfUrl", WebUtils.encodeFileName(cacheName));
|
||||
return PDF_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
else if ("jpg".equalsIgnoreCase(tifPreviewType)) {
|
||||
model.addAttribute("imgUrls", fileHandlerService.getImgCache(cacheName));
|
||||
model.addAttribute("currentUrl", fileHandlerService.getImgCache(cacheName).get(0));
|
||||
return PICTURE_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
}
|
||||
|
||||
// 处理普通TIF预览(不进行转换)
|
||||
return handleRegularTiffPreview(url, model, fileAttribute, fileName, forceUpdatedCache, outFilePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动异步TIF转换
|
||||
*/
|
||||
private void startAsyncTiffConversion(String filePath, String outFilePath, String cacheName,
|
||||
String fileName, FileAttribute fileAttribute,
|
||||
String tifPreviewType, boolean forceUpdatedCache) {
|
||||
// 启动异步转换
|
||||
CompletableFuture<Void> conversionFuture = CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
// 更新状态
|
||||
FileConvertStatusManager.startConvert(cacheName);
|
||||
FileConvertStatusManager.updateProgress(cacheName, "正在启动TIF转换", 10);
|
||||
|
||||
if ("pdf".equalsIgnoreCase(tifPreviewType)) {
|
||||
tiftoservice.convertTif2Pdf(filePath, outFilePath,fileName,cacheName, forceUpdatedCache);
|
||||
|
||||
// 转换成功,更新缓存
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath));
|
||||
}
|
||||
} else {
|
||||
List<String> listPic2Jpg = tiftoservice.convertTif2Jpg(filePath, outFilePath,fileName,cacheName, forceUpdatedCache);
|
||||
// 转换成功,更新缓存
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
fileHandlerService.putImgCache(cacheName, listPic2Jpg);
|
||||
fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath));
|
||||
}
|
||||
}
|
||||
FileConvertStatusManager.convertSuccess(cacheName);
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
// 检查是否为Bad endianness tag异常
|
||||
if (e.getMessage() != null && e.getMessage().contains("Bad endianness tag (not 0x4949 or 0x4d4d)")) {
|
||||
// 特殊处理:对于这种异常,我们不标记为转换失败,而是记录日志
|
||||
logger.warn("TIF文件格式异常(Bad endianness tag),将尝试直接预览: {}", filePath);
|
||||
FileConvertStatusManager.convertSuccess(cacheName);
|
||||
return null;
|
||||
} else {
|
||||
logger.error("TIF转换执行失败: {}", cacheName, e);
|
||||
|
||||
// 检查是否已经标记为超时
|
||||
FileConvertStatusManager.ConvertStatus status = FileConvertStatusManager.getConvertStatus(cacheName);
|
||||
if (status == null || status.getStatus() != FileConvertStatusManager.Status.TIMEOUT) {
|
||||
FileConvertStatusManager.markError(cacheName, "转换失败: " + e.getMessage());
|
||||
}
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 添加转换完成后的回调
|
||||
conversionFuture.thenRunAsync(() -> {
|
||||
try {
|
||||
// 是否保留源文件(只在转换成功后才删除)
|
||||
if (!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) {
|
||||
KkFileUtils.deleteFileByPath(filePath);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("TIF转换后续处理失败: {}", filePath, e);
|
||||
}
|
||||
}, callbackExecutor).exceptionally(throwable -> {
|
||||
// 转换失败,记录日志但不删除源文件
|
||||
logger.error("TIF转换失败,保留源文件供排查: {}", filePath, throwable);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理普通TIF预览(不进行转换)
|
||||
*/
|
||||
private String handleRegularTiffPreview(String url, Model model, FileAttribute fileAttribute,
|
||||
String fileName, boolean forceUpdatedCache, String outFilePath) {
|
||||
// 不是http开头,浏览器不能直接访问,需下载到本地
|
||||
if (url != null && !url.toLowerCase().startsWith("http")) {
|
||||
if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(fileName) || !ConfigConstants.isCacheEnabled()) {
|
||||
@@ -117,12 +184,11 @@ public class TiffFilePreviewImpl implements FilePreview {
|
||||
fileHandlerService.addConvertedFile(fileName, fileHandlerService.getRelativePath(outFilePath));
|
||||
}
|
||||
} else {
|
||||
model.addAttribute("currentUrl", WebUtils.encodeFileName(fileName));
|
||||
model.addAttribute("currentUrl", WebUtils.encodeFileName(fileName));
|
||||
}
|
||||
return TIFF_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
model.addAttribute("currentUrl", url);
|
||||
return TIFF_FILE_PREVIEW_PAGE;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user