浏览代码

上传文件接口优化,适应各种图片进行转换

fangzhen 2 天之前
父节点
当前提交
f21556b044

+ 26 - 0
ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java

@@ -150,6 +150,32 @@ public class CommonController {
             // 上传文件路径
             String fileName = OssUtils.uploadMultipartFile(file);
             System.out.println(fileName);
+
+            if ("image".equalsIgnoreCase(fileType)) {
+                String fileName_copy = fileName;
+                //对文件进行统一转换
+                if (fileName_copy.contains(".png") || fileName_copy.contains(".PNG")) {
+                    fileName_copy += "?x-oss-process=image/format,png";
+                } else if (fileName_copy.contains(".jpg") || fileName_copy.contains(".JPG")) {
+                    fileName_copy += "?x-oss-process=image/format,jpg";
+                } else if (fileName_copy.contains(".gif") || fileName_copy.contains(".GIF")) {
+                    fileName_copy += "?x-oss-process=image/format,gif";
+                } else if (fileName_copy.contains(".tiff")) {
+                    fileName_copy += "?x-oss-process=image/format,tiff";
+                } else if (fileName_copy.contains(".heic")) {
+                    fileName_copy += "?x-oss-process=image/format,png";
+                } else if (fileName_copy.contains(".avif")) {
+                    fileName_copy += "?x-oss-process=image/format,png";
+                }
+
+                //下载转化后的图片
+                String tempSourceFile = System.getProperty("java.io.tmpdir") + File.separator + "source_" + FileUtils.getName(fileName);
+                byte[] image = ImageUtils.getImage(fileName_copy);
+                ImageUtils.saveImageToLocal(image, tempSourceFile);
+                // 上传加水印的文件到OSS
+                fileName = OssUtils.uploadFile(tempSourceFile);
+            }
+
             String fileNameResult = fileName.replace("https://cysd.oss-cn-shanghai.aliyuncs.com", fileUrl);
             String thumbnailPath = "";
             String compressedFileUrl = "";

+ 6 - 6
ruoyi-admin/src/main/resources/application-druid.yml

@@ -6,12 +6,12 @@ spring:
         druid:
             # 主库数据源  47.122.10.161 121.4.140.159
             master:
-                url: jdbc:mysql://121.4.140.159:3307/ruoyi-community?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
-                username: root
-                password: fangzhen,7410
-                #url: jdbc:mysql://rm-bp12v02802jkd05j89o.mysql.rds.aliyuncs.com:3306/ruoyi-community_backup?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
-                #username: cysd
-                #password: cysd123!@#
+#                url: jdbc:mysql://121.4.140.159:3307/ruoyi-community?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
+#                username: root
+#                password: fangzhen,7410
+                url: jdbc:mysql://rm-bp12v02802jkd05j89o.mysql.rds.aliyuncs.com:3306/ruoyi-community_backup?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
+                username: cysd
+                password: cysd123!@#
             # 从库数据源
             slave:
                 # 从数据源开关/默认关闭

+ 56 - 6
ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java

@@ -284,18 +284,68 @@ public class FileUtils {
      */
     public static String getFileTypeFromUrl(String fileUrl) throws IOException {
         URL url = new URL(fileUrl);
-        try (InputStream inputStream = url.openStream()) {
-            Tika tika = new Tika();
-            String mimeType = tika.detect(inputStream);
-            if (mimeType.startsWith("image/")) {
+        
+        // 设置连接属性
+        java.net.HttpURLConnection connection = null;
+        try {
+            // 检查是否需要设置代理
+            String proxyHost = System.getProperty("http.proxyHost");
+            String proxyPort = System.getProperty("http.proxyPort");
+            
+            if (StringUtils.isNotEmpty(proxyHost) && StringUtils.isNotEmpty(proxyPort)) {
+                // 使用系统配置的代理
+                java.net.Proxy proxy = new java.net.Proxy(
+                    java.net.Proxy.Type.HTTP, 
+                    new java.net.InetSocketAddress(proxyHost, Integer.parseInt(proxyPort))
+                );
+                connection = (java.net.HttpURLConnection) url.openConnection(proxy);
+            } else {
+                connection = (java.net.HttpURLConnection) url.openConnection();
+            }
+            
+            // 设置连接参数
+            connection.setConnectTimeout(5000); // 5秒连接超时
+            connection.setReadTimeout(5000);    // 5秒读取超时
+            connection.setRequestMethod("GET");
+            connection.setDoInput(true);
+            
+            // 尝试连接
+            connection.connect();
+            
+            try (InputStream inputStream = connection.getInputStream()) {
+                Tika tika = new Tika();
+                String mimeType = tika.detect(inputStream);
+                if (mimeType.startsWith("image/")) {
+                    return "image";
+                } else if (mimeType.startsWith("audio/")) {
+                    return "audio";
+                } else if (mimeType.startsWith("video/")) {
+                    return "video";
+                } else {
+                    return "other";
+                }
+            }
+        } catch (java.net.SocketException e) {
+            // 处理网络权限错误
+            System.err.println("网络连接权限被拒绝: " + e.getMessage());
+            // 尝试从URL路径推断文件类型
+            String path = url.getPath();
+            String extension = FilenameUtils.getExtension(path).toLowerCase();
+            
+            // 根据扩展名判断文件类型
+            if (MimeTypeUtils.isImage(extension)) {
                 return "image";
-            } else if (mimeType.startsWith("audio/")) {
+            } else if (MimeTypeUtils.isAudio(extension)) {
                 return "audio";
-            } else if (mimeType.startsWith("video/")) {
+            } else if (MimeTypeUtils.isVideo(extension)) {
                 return "video";
             } else {
                 return "other";
             }
+        } finally {
+            if (connection != null) {
+                connection.disconnect();
+            }
         }
     }
 

+ 17 - 2
ruoyi-common/src/main/java/com/ruoyi/common/utils/file/ImageUtils.java

@@ -36,6 +36,22 @@ public class ImageUtils {
         }
     }
 
+    /**
+     * 保存文件到指定路径
+     *
+     * @param imageBytes    字节流
+     * @param localFilePath 本地文件路径
+     */
+    public static void saveImageToLocal(byte[] imageBytes, String localFilePath) {
+        try (FileOutputStream fos = new FileOutputStream(localFilePath)) {
+            fos.write(imageBytes);
+            System.out.println("文件已成功保存到本地: " + localFilePath);
+        } catch (IOException e) {
+            System.out.println("保存文件时出错");
+            e.printStackTrace();
+        }
+    }
+
     public static InputStream getFile(String imagePath) {
         try {
             byte[] result = readFile(imagePath);
@@ -196,8 +212,7 @@ public class ImageUtils {
      */
     public static void compressAndGenerateThumbnail(String originalImagePath, String thumbImagePath, int width, int height, float quality) throws IOException {
         // 压缩图片并生成缩略图
-        Thumbnails.of(new File(originalImagePath))
-                .size(width, height)  // 设置缩略图的宽高
+        Thumbnails.of(new File(originalImagePath)).size(width, height)  // 设置缩略图的宽高
                 .outputQuality(quality)  // 设置图片压缩质量
                 .toFile(new File(thumbImagePath));  // 输出文件
     }

+ 56 - 1
ruoyi-common/src/main/java/com/ruoyi/common/utils/file/MimeTypeUtils.java

@@ -55,4 +55,59 @@ public class MimeTypeUtils {
                 return "";
         }
     }
-}
+
+    /**
+     * 判断是否为图片扩展名
+     * @param extension 文件扩展名
+     * @return 是否为图片扩展名
+     */
+    public static boolean isImage(String extension) {
+        if (extension == null || extension.isEmpty()) {
+            return false;
+        }
+        String ext = extension.toLowerCase();
+        for (String allowedExt : IMAGE_EXTENSION) {
+            if (allowedExt.equals(ext)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 判断是否为音频扩展名
+     * @param extension 文件扩展名
+     * @return 是否为音频扩展名
+     */
+    public static boolean isAudio(String extension) {
+        if (extension == null || extension.isEmpty()) {
+            return false;
+        }
+        String ext = extension.toLowerCase();
+        String[] audioExtensions = {"mp3", "wav", "wma", "mid"};
+        for (String allowedExt : audioExtensions) {
+            if (allowedExt.equals(ext)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 判断是否为视频扩展名
+     * @param extension 文件扩展名
+     * @return 是否为视频扩展名
+     */
+    public static boolean isVideo(String extension) {
+        if (extension == null || extension.isEmpty()) {
+            return false;
+        }
+        String ext = extension.toLowerCase();
+        for (String allowedExt : VIDEO_EXTENSION) {
+            if (allowedExt.equals(ext)) {
+                return true;
+            }
+        }
+        return false;
+    }
+}

+ 1 - 1
ruoyi-common/src/main/java/com/ruoyi/common/utils/file/OssUtils.java

@@ -199,7 +199,7 @@ public class OssUtils {
                     .replaceFirst("=+$", "");
 
             // 添加水印
-            String style = "image/watermark,text_" + watermarkText + ",pady_-100,size_100,fill_1,t_30,rotate_45,type_d3F5LW1pY3JvaGVp";
+            String style = "image/watermark,text_" + watermarkText + ",pady_10,size_100,fill_1,t_30,rotate_45,type_d3F5LW1pY3JvaGVp";
             GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
             request.setProcess(style);
             // 将处理后的图片命名为example-new.jpg并保存到本地。