Ver Fonte

修复office文件密码判断

陈精华 há 2 anos atrás
pai
commit
e0cc2b6a01
1 ficheiros alterados com 12 adições e 7 exclusões
  1. 12 7
      server/src/main/java/cn/keking/utils/OfficeUtils.java

+ 12 - 7
server/src/main/java/cn/keking/utils/OfficeUtils.java

@@ -1,12 +1,13 @@
 package cn.keking.utils;
 
 import org.apache.commons.lang3.exception.ExceptionUtils;
-import org.apache.poi.EncryptedDocumentException;
 import org.apache.poi.extractor.ExtractorFactory;
 import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
 import org.springframework.lang.Nullable;
 
-import java.io.FileInputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 
 /**
  * Office工具类
@@ -16,6 +17,8 @@ import java.io.FileInputStream;
  */
 public class OfficeUtils {
 
+    private static final String POI_INVALID_PASSWORD_MSG = "Invalid password specified";
+
     /**
      * 判断office(word,excel,ppt)文件是否受密码保护
      *
@@ -24,13 +27,15 @@ public class OfficeUtils {
      */
     public static boolean isPwdProtected(String path) {
         try {
-            ExtractorFactory.createExtractor(new FileInputStream(path));
-        } catch (EncryptedDocumentException e) {
-            return true;
+            ExtractorFactory.createExtractor(Files.newInputStream(Paths.get(path)));
+        } catch (IOException e) {
+            if (POI_INVALID_PASSWORD_MSG.equals(e.getMessage())) {
+                return true;
+            }
         } catch (Exception e) {
             Throwable[] throwableArray = ExceptionUtils.getThrowables(e);
             for (Throwable throwable : throwableArray) {
-                if (throwable instanceof EncryptedDocumentException) {
+                if (throwable instanceof IOException && POI_INVALID_PASSWORD_MSG.equals(throwable.getMessage())) {
                     return true;
                 }
             }
@@ -48,7 +53,7 @@ public class OfficeUtils {
     public static synchronized boolean isCompatible(String path, @Nullable String password) {
         try {
             Biff8EncryptionKey.setCurrentUserPassword(password);
-            ExtractorFactory.createExtractor(new FileInputStream(path));
+            ExtractorFactory.createExtractor(Files.newInputStream(Paths.get(path)));
         } catch (Exception e) {
             return false;
         } finally {