This commit is contained in:
2025-12-08 14:50:27 +08:00
parent 74bee3e232
commit 6168f4c57d
25 changed files with 492 additions and 194 deletions

View File

@ -193,7 +193,7 @@ public class FileInfoController {
// 标准化路径
targetFilePath = Paths.get(fileAbsolutePath).toRealPath();
// 校验文件合法性: 是否存在、是否为普通文件
// 是否存在、是否为普通文件
BasicFileAttributes fileAttr = Files.readAttributes(targetFilePath, BasicFileAttributes.class);
if (!fileAttr.isRegularFile()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
@ -204,21 +204,27 @@ public class FileInfoController {
// 设置预览响应头
String fileName = targetFilePath.getFileName().toString();
String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
// 手动映射常见图片格式的 MIME 类型
String contentType = Files.probeContentType(targetFilePath);
String fileExtension = getFileExtension(fileName).toLowerCase();
// 覆盖默认探测结果
contentType = mapImageContentType(fileExtension, contentType);
// 对于文本类型文件、指定字符编码
if (contentType != null && contentType.startsWith("text/")) {
response.setContentType(contentType + "; charset=UTF-8");
} else {
response.setContentType(contentType != null ? contentType : "application/octet-stream");
// 确保 Content-Type 不为空
response.setContentType(contentType != null ? contentType : "image/png");
}
response.setContentLengthLong(fileAttr.size());
// 关键修改: 将attachment改为inline实现预览
// inline 已正确设置、无需修改
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"inline; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);
// 写入文件流
// 写入文件流(无需修改)
try (InputStream inputStream = Files.newInputStream(targetFilePath);
OutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[1024 * 8];
@ -240,4 +246,32 @@ public class FileInfoController {
fileInfoService.writeResponseMessage(response, "预览失败: " + e.getMessage());
}
}
/**
* 获取文件后缀
*/
private String getFileExtension(String fileName) {
int lastDotIndex = fileName.lastIndexOf('.');
return lastDotIndex == -1 ? "" : fileName.substring(lastDotIndex + 1);
}
/**
* 映射图片格式到标准 MIME 类型
*/
private String mapImageContentType(String fileExtension, String probeContentType) {
Map<String, String> imageMimeMap = new HashMap<>();
imageMimeMap.put("webp", "image/webp");
imageMimeMap.put("png", "image/png");
imageMimeMap.put("jpg", "image/jpeg");
imageMimeMap.put("jpeg", "image/jpeg");
imageMimeMap.put("gif", "image/gif");
imageMimeMap.put("bmp", "image/bmp");
imageMimeMap.put("svg", "image/svg+xml");
// 如果探针结果已存在且是图片类型
if (probeContentType != null && probeContentType.startsWith("image/")) {
return probeContentType;
}
return imageMimeMap.getOrDefault(fileExtension, probeContentType);
}
}