From 7c0603315e57e3765270a8ac6b310b5a32af5a40 Mon Sep 17 00:00:00 2001
From: zqy <2522236926@qq.com>
Date: 星期五, 02 一月 2026 15:11:13 +0800
Subject: [PATCH] 新增压缩图 和 视频封面 都返回base64

---
 ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java |  480 +++++++++++++++++++++++++++++++++++++++++++++++++++++++----
 1 files changed, 444 insertions(+), 36 deletions(-)

diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java
index adad316..308d8e7 100644
--- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java
+++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java
@@ -1,14 +1,32 @@
 package com.ruoyi.web.controller.common;
 
-import java.util.ArrayList;
-import java.util.HashMap;
+import java.io.File;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.util.*;
 import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.imageio.IIOImage;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.ImageWriter;
+import javax.imageio.stream.MemoryCacheImageOutputStream;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.websocket.server.PathParam;
 
 import com.ruoyi.common.annotation.Anonymous;
+import com.ruoyi.common.utils.RenamedMultipartFile;
+import com.ruoyi.common.utils.uuid.UUID;
 import com.ruoyi.service.DownLoadFileService;
+import com.ruoyi.service.impl.VideoProcessService;
+import lombok.Data;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -23,16 +41,32 @@
 import com.ruoyi.common.utils.file.FileUploadUtils;
 import com.ruoyi.common.utils.file.FileUtils;
 import com.ruoyi.framework.config.ServerConfig;
+import springfox.bean.validators.plugins.schema.NotNullAnnotationPlugin;
+
+import javax.imageio.ImageIO;
+
+import java.awt.*;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+import java.util.Base64;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
 
 /**
  * 閫氱敤璇锋眰澶勭悊
- * 
+ *
  * @author ruoyi
  */
 @RestController
 @RequestMapping("/common")
-public class CommonController
-{
+public class CommonController {
     private static final Logger log = LoggerFactory.getLogger(CommonController.class);
 
     @Autowired
@@ -41,9 +75,55 @@
     @Autowired
     private DownLoadFileService downLoadFileService;
 
+
+    @Autowired
+    private VideoProcessService videoProcessService;
+
     private static final String FILE_DELIMETER = ",";
 
-//    @GetMapping("/downloadFile")
+    private static final Pattern CHINESE_PATTERN = Pattern.compile("[\u4e00-\u9fa5]");
+
+    // 缂╃暐鍥鹃厤缃�
+    @Value("${thumbnail.default-width:300}")
+    private int defaultThumbnailWidth;
+
+    @Value("${thumbnail.default-height:200}")
+    private int defaultThumbnailHeight;
+
+    @Value("${thumbnail.quality:0.8}")
+    private double thumbnailQuality;
+
+    @Value("${thumbnail.cache-dir:./cache/thumbnails}")
+    private String thumbnailCacheDir;
+
+
+    @Value("${thumbnail.max-width:1920}")
+    private int maxThumbnailWidth;
+
+    @Value("${thumbnail.max-height:1080}")
+    private int maxThumbnailHeight;
+
+    @Value("${thumbnail.format:jpg}")
+    private String thumbnailFormat;
+
+    @Value("${thumbnail.keep-aspect-ratio:true}")
+    private boolean keepAspectRatio;
+
+    // 鏀寔鐨勫浘鐗囨牸寮�
+    private static final String[] IMAGE_FORMATS = {"jpg", "jpeg", "png", "gif", "bmp", "webp"};
+
+    // 鏀寔鐨勮棰戞牸寮�
+    private static final String[] VIDEO_FORMATS = {"mp4", "avi", "mov", "wmv", "flv", "mkv", "webm"};
+    @Autowired
+    private NotNullAnnotationPlugin notNullPlugin;
+
+    @Anonymous
+    @GetMapping("/generateThumbnail")
+    public AjaxResult generateThumbnail(@PathParam(value = "url") String url) throws Exception {
+
+        return AjaxResult.success( );
+    }
+    //    @GetMapping("/downloadFile")
 //    public void fileDownload(@PathParam("path") String path, HttpServletResponse response)
 //    {
 //        path=path.substring(8);
@@ -68,9 +148,7 @@
 //    }
 
 
-
-
-//    /**
+    //    /**
 //     * 閫氱敤涓嬭浇璇锋眰
 //     *
 //     * @param fileName 鏂囦欢鍚嶇О
@@ -101,11 +179,11 @@
 //            log.error("涓嬭浇鏂囦欢澶辫触", e);
 //        }
 //    }
-@Anonymous
+    @Anonymous
 
     @GetMapping("/downLoadFile")
     public void downLoadFile(@PathParam("path") String path, HttpServletResponse response) throws Exception {
-        downLoadFileService.downLoadFile(path,response);
+        downLoadFileService.downLoadFile(path, response);
     }
 
 
@@ -113,14 +191,12 @@
      * 閫氱敤涓婁紶璇锋眰锛堝崟涓級
      */
     @PostMapping("/upload")
-    public AjaxResult uploadFile(@RequestParam("uploadFile") MultipartFile file,String fname) throws Exception
-    {
-        try
-        {
+    public AjaxResult uploadFile(@RequestParam("uploadFile") MultipartFile file, String fname) throws Exception {
+        try {
             // 涓婁紶鏂囦欢璺緞
             String filePath = RuoYiConfig.getUploadPath();
             // 涓婁紶骞惰繑鍥炴柊鏂囦欢鍚嶇О
-            String fileName = FileUploadUtils.upload(filePath, file,fname);
+            String fileName = FileUploadUtils.upload(filePath, file, fname);
             String url = serverConfig.getUrl() + fileName;
 
             AjaxResult ajax = AjaxResult.success();
@@ -131,15 +207,14 @@
             data.put("newFileName", FileUtils.getName(fileName));
             data.put("originalFilename", file.getOriginalFilename());
 
-            ajax.put("msg","鎿嶄綔鎴愬姛");
-            ajax.put("data",data);
+            ajax.put("msg", "鎿嶄綔鎴愬姛");
+            ajax.put("data", data);
             return ajax;
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             return AjaxResult.error(e.getMessage());
         }
     }
+
 
     /**
      * 閫氱敤涓婁紶璇锋眰锛堝涓級
@@ -156,15 +231,15 @@
             List<String> fileNames = new ArrayList<String>();
             List<String> newFileNames = new ArrayList<String>();
             List<String> originalFilenames = new ArrayList<String>();
-           // System.out.println("99999999999999999999999990000000000000000");
-          //  System.out.println(files);
-          //  System.out.println(files.size());
+            // System.out.println("99999999999999999999999990000000000000000");
+            //  System.out.println(files);
+            //  System.out.println(files.size());
 
             for (MultipartFile file : files)
             {
                 // 涓婁紶骞惰繑鍥炴柊鏂囦欢鍚嶇О
                 String filename = "";
-             //   System.out.println("1122123330+++++++++++++++++++++++++++++");
+                //   System.out.println("1122123330+++++++++++++++++++++++++++++");
 
                 String fileName = FileUploadUtils.upload(filePath, file, filename);
                 String url = serverConfig.getUrl() + fileName;
@@ -174,13 +249,13 @@
                 originalFilenames.add(file.getOriginalFilename());
             }
             AjaxResult ajax = AjaxResult.success();
-          //  System.out.println("99999999999999999999999990000000000000000");
+            //  System.out.println("99999999999999999999999990000000000000000");
 
             ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
             ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
             ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
             ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
-          //  System.out.println("1122123330+++++++++++++++++++++++++++++");
+            //  System.out.println("1122123330+++++++++++++++++++++++++++++");
             return ajax;
         }
         catch (Exception e)
@@ -190,16 +265,235 @@
     }
 
     /**
+     * 閫氱敤涓婁紶璇锋眰锛堝涓級 灏嗕腑鏂囦慨鏀逛负鍏朵粬
+     */
+    @PostMapping("/noChinese/uploads")
+    public AjaxResult noChineseUploadFiles(@RequestParam("files") List<MultipartFile> files) throws Exception {
+        //System.out.println("99999999999999999999999990000000000000000");
+        try {
+            // 涓婁紶鏂囦欢璺緞
+            String filePath = RuoYiConfig.getUploadPath();
+            List<String> urls = new ArrayList<String>();
+            List<String> fileNames = new ArrayList<String>();
+            List<String> newFileNames = new ArrayList<String>();
+            List<String> originalFilenames = new ArrayList<String>();
+
+            for (MultipartFile file : files) {
+                originalFilenames.add(file.getOriginalFilename());
+
+                String safeFilename = generateSafeFilename(file.getOriginalFilename());
+
+                MultipartFile renamedFile = new RenamedMultipartFile(file, safeFilename);
+
+                String lastName="";
+
+                String fileName = FileUploadUtils.upload(filePath, renamedFile, lastName);
+
+                String url = serverConfig.getUrl() + fileName;
+                urls.add(url);
+                fileNames.add(fileName);
+                newFileNames.add(FileUtils.getName(fileName));
+            }
+            AjaxResult ajax = AjaxResult.success();
+
+            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
+            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
+            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
+            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
+            return ajax;
+        } catch (Exception e) {
+            return AjaxResult.error(e.getMessage());
+        }
+    }
+
+    /**
+     * 鐢熸垚瀹夊叏鏂囦欢鍚嶏紙鍙浛鎹腑鏂囬儴鍒嗭級
+     */
+    private String generateSafeFilename(String originalName) {
+        if (originalName == null) {
+            return "";
+        }
+
+        // 1. 鑾峰彇鏂囦欢鎵╁睍鍚�
+        String extension = "";
+        int dotIndex = originalName.lastIndexOf('.');
+        if (dotIndex > 0) {
+            extension = originalName.substring(dotIndex);
+            originalName = originalName.substring(0, dotIndex);
+        }
+
+        // 2. 鍙浛鎹腑鏂囬儴鍒�
+        StringBuilder safeName = new StringBuilder();
+        Matcher matcher = CHINESE_PATTERN.matcher(originalName);
+        int lastEnd = 0;
+
+        while (matcher.find()) {
+            // 娣诲姞闈炰腑鏂囬儴鍒�
+            safeName.append(originalName, lastEnd, matcher.start());
+
+            // 娣诲姞闅忔満瀛楃涓叉浛鎹腑鏂�
+            safeName.append(generateRandomString(4));
+
+            lastEnd = matcher.end();
+        }
+
+        // 娣诲姞鍓╀綑閮ㄥ垎
+        safeName.append(originalName.substring(lastEnd));
+        String noSpaceName = safeName.toString().replaceAll("\\s", "");
+
+        // 3. 娣诲姞鎵╁睍鍚�
+        return noSpaceName + extension;
+    }
+    /**
+     * 鐢熸垚闅忔満瀛楃涓诧紙瀛楁瘝+鏁板瓧锛�
+     */
+    private String generateRandomString(int length) {
+        String uuid = UUID.randomUUID().toString().replace("-", "");
+        return uuid.substring(0, Math.min(length, uuid.length()));
+    }
+
+
+    @PostMapping("/uploads1")
+    public AjaxResult uploadFiles1(@RequestParam("files") List<MultipartFile> files) {
+        try {
+            String filePath = RuoYiConfig.getUploadPath();
+            List<String> urls = new ArrayList<>();
+            List<String> fileNames = new ArrayList<>();
+            List<String> newFileNames = new ArrayList<>();
+            List<String> originalFilenames = new ArrayList<>();
+            List<String> httpSafePaths = new ArrayList<>();
+
+            for (MultipartFile file : files) {
+                // 1. 涓婁紶鏂囦欢
+                String fileName = FileUploadUtils.upload(filePath, file, "");
+                String originalFilename = file.getOriginalFilename();
+
+                // 2. 鑾峰彇HTTP瀹夊叏璺緞
+                String httpSafePath = toHttpPath(fileName);
+
+                // 3. 鏋勫缓瀹屾暣URL锛堢‘淇濇湁鏂滄潬鍒嗛殧锛�
+                String baseUrl = serverConfig.getUrl();
+                if (!baseUrl.endsWith("/") && !httpSafePath.startsWith("/")) {
+                    baseUrl += "/";
+                }
+                String url = baseUrl + httpSafePath;
+
+                urls.add(url);
+                fileNames.add(fileName);
+                newFileNames.add(FileUtils.getName(fileName));
+                originalFilenames.add(originalFilename);
+                httpSafePaths.add(httpSafePath);
+            }
+
+            AjaxResult ajax = AjaxResult.success();
+            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
+            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
+            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
+            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
+            ajax.put("httpSafePaths", StringUtils.join(httpSafePaths, FILE_DELIMETER));
+            return ajax;
+        } catch (Exception e) {
+            return AjaxResult.error(e.getMessage());
+        }
+    }
+
+
+    /**
+     * 灏嗗寘鍚腑鏂囩殑鏂囦欢璺緞杞崲涓� HTTP 瀹夊叏鐨� URL 璺緞
+     */
+
+    public String toHttpPath(String filePath) {
+        try {
+            // 1. 鏍囧噯鍖栬矾寰�
+            Path normalizedPath = Paths.get(filePath).normalize();
+
+            // 2. 缁熶竴浣跨敤姝f枩鏉�
+            String pathStr = normalizedPath.toString().replace("\\", "/");
+
+            // 3. 鍒嗗壊璺緞缁勪欢
+            String[] parts = pathStr.split("/");
+            StringBuilder encodedPath = new StringBuilder();
+
+            // 4. 瀵规瘡涓粍浠跺崟鐙紪鐮佸苟澶勭悊绌烘牸
+            for (String part : parts) {
+                if (!part.isEmpty()) {
+                    // 缂栫爜骞舵浛鎹㈢┖鏍间负 %20
+                    String encodedPart = URLEncoder.encode(part, StandardCharsets.UTF_8.name())
+                            .replace("+", "%20");
+                    encodedPath.append("/").append(encodedPart);
+                }
+            }
+
+            // 5. 澶勭悊缁濆璺緞鍜岀浉瀵硅矾寰�
+            return filePath.startsWith("/") || filePath.startsWith("\\") ?
+                    encodedPath.toString() :
+                    encodedPath.substring(1);
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException("UTF-8 encoding not supported", e);
+        }
+        }
+
+    /**
+     * 浠� HTTP URL 璺緞杩樺師鍘熷涓枃璺緞
+     */
+    @PostMapping("/getFileName")
+    public String extractFileName(@RequestBody String httpPath) {
+        try {
+            // 1. 澶勭悊绌哄��
+            if (httpPath == null || httpPath.trim().isEmpty()) {
+                return "";
+            }
+
+            // 2. 绉婚櫎URL鍗忚銆佸煙鍚嶅拰鏌ヨ鍙傛暟
+            String pathOnly = httpPath;
+
+            // 绉婚櫎鍗忚鍜屽煙鍚�
+            if (pathOnly.contains("://")) {
+                pathOnly = pathOnly.substring(pathOnly.indexOf("://") + 3);
+                pathOnly = pathOnly.substring(pathOnly.indexOf('/'));
+            }
+
+            // 绉婚櫎鏌ヨ鍙傛暟锛堝 ?token=123锛�
+            int queryStart = pathOnly.indexOf('?');
+            if (queryStart > 0) {
+                pathOnly = pathOnly.substring(0, queryStart);
+            }
+
+            // 3. URL瑙g爜
+            String decodedPath = URLDecoder.decode(pathOnly, StandardCharsets.UTF_8.name());
+
+            // 4. 鎻愬彇鏂囦欢鍚嶏紙澶勭悊Windows璺緞锛�
+            decodedPath = decodedPath.replace("\\", "/");
+
+            // 鑾峰彇鏈�鍚庝竴涓潪绌鸿矾寰勭粍浠�
+            int lastSlash = decodedPath.lastIndexOf('/');
+            String fileName = (lastSlash >= 0 && lastSlash < decodedPath.length() - 1) ?
+                    decodedPath.substring(lastSlash + 1) : decodedPath;
+
+            // 5. 澶勭悊鐗规畩鎯呭喌锛堝缁撳熬鏂滄潬锛�
+            if (fileName.isEmpty()) {
+                // 灏濊瘯鑾峰彇鍊掓暟绗簩涓粍浠�
+                int prevSlash = decodedPath.lastIndexOf('/', lastSlash - 1);
+                if (prevSlash >= 0) {
+                    fileName = decodedPath.substring(prevSlash + 1, lastSlash);
+                }
+            }
+
+            return fileName;
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException("UTF-8 encoding not supported", e);
+        }
+    }
+
+
+    /**
      * 鏈湴璧勬簮閫氱敤涓嬭浇
      */
     @GetMapping("/download/resource")
     public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
-            throws Exception
-    {
-        try
-        {
-            if (!FileUtils.checkAllowDownload(resource))
-            {
+            throws Exception {
+        try {
+            if (!FileUtils.checkAllowDownload(resource)) {
                 throw new Exception(StringUtils.format("璧勬簮鏂囦欢({})闈炴硶锛屼笉鍏佽涓嬭浇銆� ", resource));
             }
             // 鏈湴璧勬簮璺緞
@@ -211,10 +505,124 @@
             response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
             FileUtils.setAttachmentResponseHeader(response, downloadName);
             FileUtils.writeBytes(downloadPath, response.getOutputStream());
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             log.error("涓嬭浇鏂囦欢澶辫触", e);
         }
+
     }
+
+
+
+    /**
+     * 鍘嬬缉鍥剧墖鎴栨彁鍙栬棰戝皝闈㈠苟杩斿洖Base64
+     *
+     * @param file 鍥剧墖鎴栬棰戞枃浠�
+     * @param width 鐩爣瀹藉害锛岄粯璁�100
+     * @param height 鐩爣楂樺害锛岄粯璁�100
+     * @param quality 鍥剧墖璐ㄩ噺 0.1-1.0锛岄粯璁�0.8
+     * @return Map鍖呭惈鍘嬬缉缁撴灉鍜孊ase64
+     */
+    @Anonymous
+    @PostMapping(value = "/zip", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
+    public Map<String, Object> compressMediaToBase64(
+        @RequestParam(value = "file", required = false) MultipartFile file,
+        @RequestParam(value = "filePath", required = false) String filePath,
+        @RequestParam(value = "width", defaultValue = "0") int width,
+        @RequestParam(value = "height", defaultValue = "0") int height,
+        @RequestParam(value = "quality", defaultValue = "0.8") float quality) {
+        Map<String, Object> result = new HashMap<>();
+
+        File trueFile;
+        boolean deleteY = true;
+
+        try {
+            // 楠岃瘉鏂囦欢
+            if ((file == null || file.isEmpty()) && filePath == null ) {
+                result.put("success", false);
+                result.put("message", "鏂囦欢涓嶈兘涓虹┖");
+                return result;
+            }
+
+            if ((file == null || file.isEmpty())){
+                deleteY = false;
+                String fileUel = RuoYiConfig.getProfile() + filePath.replace("/profile","");
+                trueFile = new File(fileUel);
+            }else {
+                trueFile = videoProcessService.convertToFile(file);
+            }
+            String fileName = trueFile.getName();
+            if (fileName.isEmpty() && filePath == null) {
+                result.put("success", false);
+                result.put("message", "鏂囦欢鍚嶄笉鑳戒负绌�");
+                return result;
+            }
+
+            System.out.println("-----------"+fileName);
+
+            // 鑾峰彇鏂囦欢鎵╁睍鍚�
+            String extension = getFileExtension(fileName).toLowerCase();
+            System.out.println("-----------"+extension);
+
+            // 鍒ゆ柇鏂囦欢绫诲瀷
+            if (isImageFile(extension)) {
+                // 澶勭悊鍥剧墖鏂囦欢
+                return videoProcessService.processImage(trueFile, width, height, quality, extension,deleteY);
+            } else if (isVideoFile(extension)) {
+                // 澶勭悊瑙嗛鏂囦欢
+                return videoProcessService.processVideo(trueFile,width,height,quality,extension,deleteY);
+            } else {
+                result.put("success", false);
+                result.put("message", "涓嶆敮鎸佺殑鏂囦欢鏍煎紡锛�" + extension);
+                return result;
+            }
+
+        } catch (Exception e) {
+            log.error("鏂囦欢澶勭悊澶辫触", e);
+            result.put("success", false);
+            result.put("message", "澶勭悊澶辫触: " + e.getMessage());
+            return result;
+        }
+    }
+
+    /**
+     * 鍒ゆ柇鏄惁鏄浘鐗囨枃浠�
+     */
+    private boolean isImageFile(String extension) {
+        for (String format : IMAGE_FORMATS) {
+            if (format.equalsIgnoreCase(extension)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 鍒ゆ柇鏄惁鏄棰戞枃浠�
+     */
+    private boolean isVideoFile(String extension) {
+        for (String format : VIDEO_FORMATS) {
+            if (format.equalsIgnoreCase(extension)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 鑾峰彇鏂囦欢鎵╁睍鍚�
+     */
+    private String getFileExtension(String fileName) {
+        if (StringUtils.isEmpty(fileName)) {
+            return "";
+        }
+
+        int lastDot = fileName.lastIndexOf('.');
+        if (lastDot > 0 && lastDot < fileName.length() - 1) {
+            return fileName.substring(lastDot + 1).toLowerCase();
+        }
+        return "";
+    }
+
+
+
 }

--
Gitblit v1.9.1