Просмотр исходного кода

fix(eds): 媒体文件按 UUID 落盘并修复 zip 文件名 GBK 解码

- 落盘文件名统一为 UUID + 安全扩展名,避免中文/乱码文件名进入 URL
- 同一源文件被多行引用时复用首次落盘路径,避免重复复制
- 7-Zip 解压指定 -mcp=936,修复无 UTF-8 标记的 GBK 条目名被按 CP437 解码
- 补充非 ASCII 文件名与媒体路径复用测试
cc 3 недель назад
Родитель
Сommit
6f3f7416b9

+ 26 - 3
ai-server/src/main/java/com/zsjz/ai/common/utils/LocalFileStorageUtil.java

@@ -24,6 +24,7 @@ import java.time.OffsetDateTime;
 import java.time.ZoneId;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Locale;
 import java.util.UUID;
 import java.util.stream.Stream;
 
@@ -167,8 +168,11 @@ public class LocalFileStorageUtil {
     /**
      * 保存 EDS 数据包内解压出的媒体文件。
      *
-     * <p>存储路径:{@code <eds-dir>/<yyyy-MM-dd>/<md5(采集编号)>/<文件名>},
-     * 返回相对存储根目录的路径,可交给 {@link #getPublicUrl(String)} 生成访问地址。</p>
+     * <p>存储路径:{@code <eds-dir>/<yyyy-MM-dd>/<md5(采集编号)>/<uuid>.<原扩展名>}。
+     * 落盘文件统一用 UUID 重命名:包内原始文件名可能带非 ASCII 字符或编码错乱
+     * (BCP 文本按错误字符集解码时会变成乱码),直接作为路径既可能打不开,也会让
+     * URL 出现大量百分号编码。原始文件名仍由调用方写入 {@code media_name},用于展示;
+     * 落盘路径不再携带原始名。</p>
      *
      * @param source          解压目录中的媒体文件
      * @param collectTargetId 采集编号,用于生成目录名
@@ -178,7 +182,7 @@ public class LocalFileStorageUtil {
         if (source == null || !source.isFile()) {
             return null;
         }
-        String relativePath = buildEdsMediaPath(source.getName(), collectTargetId);
+        String relativePath = buildEdsMediaPath(storedMediaFileName(source), collectTargetId);
         Path target = resolve(relativePath);
         try {
             Files.createDirectories(target.getParent());
@@ -190,6 +194,25 @@ public class LocalFileStorageUtil {
         }
     }
 
+    /**
+     * 生成落盘文件名:UUID + 安全扩展名。
+     *
+     * <p>扩展名只接受 ASCII 字母/数字(最多 10 位),避免把乱码或超长后缀带进路径;
+     * 无法识别时保留无扩展名的 UUID,由静态资源按内容类型回退。</p>
+     */
+    private static String storedMediaFileName(File source) {
+        String fileName = source.getName();
+        int dot = fileName == null ? -1 : fileName.lastIndexOf('.');
+        String extension = "";
+        if (dot >= 0 && dot < fileName.length() - 1) {
+            String candidate = fileName.substring(dot + 1);
+            if (candidate.matches("[A-Za-z0-9]{1,10}")) {
+                extension = "." + candidate.toLowerCase(Locale.ROOT);
+            }
+        }
+        return UUID.randomUUID().toString().replace("-", "") + extension;
+    }
+
     private String buildEdsMediaPath(String fileName, String collectTargetId) {
         String cid = collectTargetId == null ? "" : collectTargetId;
         String cidHash = DigestUtils.md5DigestAsHex(cid.getBytes(StandardCharsets.UTF_8));

+ 4 - 0
ai-server/src/main/java/com/zsjz/ai/common/utils/Z7.java

@@ -38,6 +38,10 @@ public class Z7 {
         command.add(zipPath.toString());
         command.add("-o" + destPath);
         command.add("-aoa");
+        // EDS 包内中文文件名多为 GBK,且 zip 条目未带 UTF-8 标记;7-Zip 默认按本地代码页
+        // 解码会把“没有涉嫌文件”解成 CP437 乱码。固定按 936 解码,带 UTF-8 标记的条目
+        // 仍会按 UTF-8 处理(两种包都验证过)。
+        command.add("-mcp=936");
         if (StrUtil.isNotEmpty(password)) {
             command.add("-p" + password);
         }

+ 33 - 0
ai-server/src/main/java/com/zsjz/ai/module/eds/utils/DataCountInfo.java

@@ -57,6 +57,14 @@ public class DataCountInfo {
      */
     private final Set<String> uploadedMediaFiles = ConcurrentHashMap.newKeySet();
 
+    /**
+     * 源文件绝对路径 → 已落盘的相对路径。
+     *
+     * <p>落盘名是 UUID,同一源文件被多行引用时必须复用首次上传结果,否则会重复复制
+     * 出多份文件;包内媒体扫描也依赖 {@link #uploadedMediaFiles} 跳过已引用文件。</p>
+     */
+    private final Map<String, String> storedMediaPaths = new ConcurrentHashMap<>();
+
 
     public DataCountInfo(String cid) {
         this.collectTargetId = cid;
@@ -221,6 +229,31 @@ public class DataCountInfo {
         }
     }
 
+    /**
+     * 记录已引用媒体文件及其落盘相对路径。
+     *
+     * @param absolutePath 解压目录中媒体文件的绝对路径
+     * @param storedPath   首次落盘后的相对路径(UUID 文件名)
+     */
+    public void markMediaUploaded(String absolutePath, String storedPath) {
+        if (StrUtil.isNotBlank(absolutePath)) {
+            uploadedMediaFiles.add(absolutePath);
+            if (StrUtil.isNotBlank(storedPath)) {
+                storedMediaPaths.putIfAbsent(absolutePath, storedPath);
+            }
+        }
+    }
+
+    /**
+     * 取同一源文件已落盘的相对路径。
+     *
+     * @param absolutePath 解压目录中媒体文件的绝对路径
+     * @return 已落盘路径;首次上传或未记录时返回 {@code null}
+     */
+    public String getStoredMediaPath(String absolutePath) {
+        return StrUtil.isBlank(absolutePath) ? null : storedMediaPaths.get(absolutePath);
+    }
+
     /**
      * 是否已被表字段引用并上传。
      *

+ 11 - 7
ai-server/src/main/java/com/zsjz/ai/module/eds/xml/EdsMediaUploader.java

@@ -198,15 +198,19 @@ public final class EdsMediaUploader {
                     }
                     //取扩展名
                     String extName = StrUtil.emptyToDefault(FileNameUtil.getSuffix(file), FileNameUtil.getSuffix(filename));
-                    //执行复制上传
+                    //同一源文件可能被多行引用:复用首次落盘的 UUID 路径,避免重复复制
+                    String absolutePath = filePath.toAbsolutePath().normalize().toString();
                     LocalFileStorageUtil fileStorage = storage();
-                    String storedPath = fileStorage.storeEdsMedia(file, cid);
+                    String storedPath = dataCountInfo == null ? null : dataCountInfo.getStoredMediaPath(absolutePath);
                     if (StrUtil.isEmpty(storedPath)) {
-                        return null;
-                    }
-                    //记录已引用文件,供扫描包内未被引用的媒体文件时去重
-                    if (dataCountInfo != null) {
-                        dataCountInfo.markMediaUploaded(filePath.toAbsolutePath().normalize().toString());
+                        storedPath = fileStorage.storeEdsMedia(file, cid);
+                        if (StrUtil.isEmpty(storedPath)) {
+                            return null;
+                        }
+                        //记录已引用文件,供扫描包内未被引用的媒体文件时去重
+                        if (dataCountInfo != null) {
+                            dataCountInfo.markMediaUploaded(absolutePath, storedPath);
+                        }
                     }
                     String fileUrl = fileStorage.getPublicUrl(storedPath);
                     fileField.set(data, fileUrl);

+ 19 - 2
ai-server/src/test/java/com/zsjz/ai/common/utils/LocalFileStorageUtilTest.java

@@ -8,6 +8,7 @@ import java.nio.file.Files;
 import java.nio.file.Path;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -35,7 +36,9 @@ class LocalFileStorageUtilTest {
 
         assertNotNull(relativePath);
         assertTrue(relativePath.startsWith("eds/"));
-        assertTrue(relativePath.endsWith("/wx2_head.jpg"));
+        assertTrue(relativePath.endsWith(".jpg"));
+        String storedName = Path.of(relativePath).getFileName().toString();
+        assertTrue(storedName.matches("[0-9a-f]{32}\\.jpg"), "落盘文件名应为 UUID: " + storedName);
 
         Path stored = storage.resolve(relativePath);
         assertTrue(Files.isRegularFile(stored));
@@ -43,7 +46,21 @@ class LocalFileStorageUtilTest {
 
         String url = storage.getPublicUrl(relativePath);
         assertTrue(url.startsWith("http://localhost:8980/js/a/files/eds/"));
-        assertTrue(url.endsWith("/wx2_head.jpg"));
+        assertTrue(url.endsWith("/" + storedName));
+    }
+
+    @Test
+    void renamesNonAsciiSourceToUuidAndKeepsSuffix() throws Exception {
+        LocalFileStorageUtil storage = new LocalFileStorageUtil(
+                tempDir.toString(), "http://localhost:8980/js/a", "eds");
+        Path source = tempDir.resolve("中文图片.jpg");
+        Files.writeString(source, "image-bytes", StandardCharsets.UTF_8);
+
+        String relativePath = storage.storeEdsMedia(source.toFile(), "CID-001");
+
+        assertNotNull(relativePath);
+        assertFalse(relativePath.contains("中文图片"), "落盘路径不应带原始中文名: " + relativePath);
+        assertTrue(Path.of(relativePath).getFileName().toString().matches("[0-9a-f]{32}\\.jpg"));
     }
 
     @Test

+ 15 - 0
ai-server/src/test/java/com/zsjz/ai/module/eds/utils/DataCountInfoTest.java

@@ -11,6 +11,8 @@ import java.util.List;
 
 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
  * 目录树计数回归测试。
@@ -70,4 +72,17 @@ class DataCountInfoTest {
 
         assertEquals(0, Eds.getDeleteNum(fieldInfo, List.of(new Object())));
     }
+
+    @Test
+    void storedMediaPathIsReusedForSameSource() {
+        DataCountInfo info = new DataCountInfo("cid");
+        String source = "C:/tmp/a.jpg";
+        String stored = "eds/2026-11-02/hash/uuid.jpg";
+
+        info.markMediaUploaded(source, stored);
+
+        assertTrue(info.isMediaUploaded(source));
+        assertEquals(stored, info.getStoredMediaPath(source));
+        assertNull(info.getStoredMediaPath("C:/tmp/other.jpg"));
+    }
 }