Преглед изворни кода

使用 tika 库替换 linux file 命令检测文件的 mime type

reghao пре 2 година
родитељ
комит
275d4ba413
2 измењених фајлова са 29 додато и 1 уклоњено
  1. 6 0
      oss-store/pom.xml
  2. 23 1
      oss-store/src/main/java/cn/reghao/oss/store/util/FileType.java

+ 6 - 0
oss-store/pom.xml

@@ -125,6 +125,12 @@
             <version>2.12.0</version>
         </dependency>
 
+        <dependency>
+            <groupId>org.apache.tika</groupId>
+            <artifactId>tika-parsers</artifactId>
+            <version>1.28.4</version>
+        </dependency>
+
         <dependency>
             <groupId>io.jsonwebtoken</groupId>
             <artifactId>jjwt</artifactId>

+ 23 - 1
oss-store/src/main/java/cn/reghao/oss/store/util/FileType.java

@@ -3,17 +3,39 @@ package cn.reghao.oss.store.util;
 import cn.reghao.jutil.jdk.shell.Shell;
 import cn.reghao.oss.api.constant.ObjectType;
 import cn.reghao.oss.api.constant.VideoUrlType;
+import org.apache.tika.Tika;
+import org.apache.tika.metadata.Metadata;
+
+import java.io.FileInputStream;
 
 /**
  * @author reghao
  * @date 2023-06-12 22:47:06
  */
 public class FileType {
-    public static String getMediaType(String src) {
+    private final static Tika tika = new Tika();
+
+    public static String getMediaType1(String src) {
         String cmd = String.format("/bin/file -b --mime-type \"%s\"", src);
         return Shell.execWithResult(cmd);
     }
 
+    public static String getMediaType(String src) {
+        try {
+            FileInputStream fis = new FileInputStream(src);
+            Metadata metadata = new Metadata();
+            tika.parse(fis, metadata);
+            String mediaType = metadata.get("Content-Type");
+            if (mediaType != null) {
+                return mediaType;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        return "application/octet-stream";
+    }
+
     public static int getFileType(String contentType) {
         int fileType = ObjectType.Other.getCode();
         if (contentType == null) {