Эх сурвалжийг харах

获取文件流时 取消synchronized关键字

chenr 3 сар өмнө
parent
commit
184d982373

+ 46 - 2
blade-common/src/main/java/org/springblade/common/utils/CommonUtil.java

@@ -140,7 +140,7 @@ public class CommonUtil {
     /**
      * 根据OSS文件路径获取文件输入流
      */
-    public static synchronized InputStream getOSSInputStream(String urlStr) {
+    public static  InputStream getOSSInputStream(String urlStr) {
         try {
             System.out.println("----前-------"+urlStr);
             urlStr = replaceOssUrl(urlStr);
@@ -183,7 +183,7 @@ public class CommonUtil {
     /**
      * 获取字节数组
      */
-    public static synchronized byte[] InputStreamToBytes(InputStream is) {
+    public static  byte[] InputStreamToBytes(InputStream is) {
         BufferedInputStream bis = new BufferedInputStream(is);
         ByteArrayOutputStream os = new ByteArrayOutputStream();
         int date = -1;
@@ -512,6 +512,50 @@ public class CommonUtil {
         //返回响应报文头字段Content-Length的值
         return urlConnection.getContentLength();
     }
+    public static long getFileContentLength(String urlStr) {
+        try {
+            urlStr = replaceOssUrl(urlStr);
+            System.out.println("获取文件大小:"+urlStr);
+            URL url = new URL(urlStr);
+            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+            // 设置 HEAD 请求(只获取头部信息,不下载文件)
+            conn.setRequestMethod("HEAD");
+            // 设置超时(避免线上卡死)
+            conn.setConnectTimeout(5000); // 5秒连接超时
+            conn.setReadTimeout(5000);    // 5秒读取超时
+            // 发起请求
+            conn.connect();
+            // 获取 Content-Length
+            long contentLength = conn.getContentLengthLong();
+            // 关闭连接
+            conn.disconnect();
+            return contentLength;
+        } catch (Exception e) {
+            return 0L;
+        }
+    }
+    public static long getFileSize(String fileUrl) throws IOException {
+        URL url = new URL(fileUrl);
+        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+
+        // 使用 HEAD 请求(只获取文件信息,不下载内容)
+        conn.setRequestMethod("HEAD");
+
+        // 设置超时(避免卡死)
+        conn.setConnectTimeout(5000); // 5秒连接超时
+        conn.setReadTimeout(5000);    // 5秒读取超时
+
+        // 发起请求
+        conn.connect();
+
+        // 获取 Content-Length(文件大小)
+        long fileSize = conn.getContentLengthLong();
+
+        // 关闭连接
+        conn.disconnect();
+
+        return fileSize;
+    }
 
 
     /**