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

图片上传压缩,优化ios推送

xiaoshushu пре 4 година
родитељ
комит
4f134d60df

+ 21 - 20
ruoyi-app/src/main/java/com/ruoyi/app/controller/base/AppCommonController.java

@@ -1,5 +1,6 @@
 package com.ruoyi.app.controller.base;
 
+import com.ruoyi.app.util.ImageCompressUtil;
 import com.ruoyi.common.config.RuoYiConfig;
 import com.ruoyi.common.constant.Constants;
 import com.ruoyi.common.core.domain.AjaxResult;
@@ -21,13 +22,15 @@ import org.springframework.web.multipart.MultipartHttpServletRequest;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.util.Random;
 
 /**
  * 通用请求处理
  */
-@Api(value = "通用请求处理",tags = "通用请求处理")
+@Api(value = "通用请求处理", tags = "通用请求处理")
 @RestController
-@RequestMapping("/app" )
+@RequestMapping("/app")
 public class AppCommonController {
     private static final Logger log = LoggerFactory.getLogger(AppCommonController.class);
 
@@ -36,18 +39,15 @@ public class AppCommonController {
 
     /**
      * 通用下载请求
-     * 
+     *
      * @param fileName 文件名称
-     * @param delete 是否删除
+     * @param delete   是否删除
      */
     @ApiOperation(value = "通用下载请求", notes = "通用下载请求")
     @GetMapping("/common/download")
-    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
-    {
-        try
-        {
-            if (!FileUtils.isValidFilename(fileName))
-            {
+    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
+        try {
+            if (!FileUtils.isValidFilename(fileName)) {
                 throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
             }
             String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
@@ -58,13 +58,10 @@ public class AppCommonController {
             response.setHeader("Content-Disposition",
                     "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
             FileUtils.writeBytes(filePath, response.getOutputStream());
-            if (delete)
-            {
+            if (delete) {
                 FileUtils.deleteFile(filePath);
             }
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             log.error("下载文件失败", e);
         }
     }
@@ -72,24 +69,28 @@ public class AppCommonController {
     /**
      * 通用上传请求
      */
-    @ApiOperation(value = "通用上传请求", notes = "通用上传请求")
+    @ApiOperation(value = "通用上传请求(带压缩,仅限图片)", notes = "通用上传请求(带压缩,仅限图片)")
     @PostMapping("/common/upload")
     public AjaxResult uploadFile(MultipartFile file) throws Exception {
-        try
-        {
+        try {
             // 上传文件路径
             String filePath = RuoYiConfig.getUploadPath();
             // 上传并返回新文件名称
             String fileName = FileUploadUtils.upload(filePath, file);
-            String url = serverConfig.getUrl() + fileName;
+            String newImg = System.currentTimeMillis() + new Random().nextInt(10000) + ".jpg";
+            ImageCompressUtil.zipImageFile(new File(filePath + fileName.replace("/profile/upload", "")), new File(RuoYiConfig.getUploadPath() + "/" + newImg));
+            //删掉压缩前的图片
+            FileUtils.deleteFile(filePath + fileName.replace("/profile/upload", ""));
+            String url = serverConfig.getUrl() + newImg;
             AjaxResult ajax = AjaxResult.success();
-            ajax.put("fileName", fileName);
+            ajax.put("fileName", "/profile/upload/" + newImg);
             ajax.put("url", url);
             return ajax;
         } catch (Exception e) {
             return AjaxResult.error(e.getMessage());
         }
     }
+
     /**
      * 图片上传请求
      */

+ 3 - 3
ruoyi-app/src/main/java/com/ruoyi/app/interceptor/AuthenticationInterceptor.java

@@ -48,19 +48,19 @@ public class AuthenticationInterceptor implements HandlerInterceptor {
         // 执行认证
         if (token == null) {
             //throw new RuntimeException("无token,请重新登录");
-            ServletUtils.renderString(httpServletResponse, JSON.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED, "无token,请重新登录")));
+            ServletUtils.renderString(httpServletResponse, JSON.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED, "未登陆,请先登录")));
             return false;
         }
         // 获取 token 中的 loginUser
         AppLoginUser loginUser = appTokenService.getLoginUser(token);
         if (loginUser == null) {
            // throw new RuntimeException("用户不存在,请重新登录");
-            ServletUtils.renderString(httpServletResponse, JSON.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED, "用户不存在,请重新登录")));
+            ServletUtils.renderString(httpServletResponse, JSON.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED, "未登陆,请先登录")));
             return false;
         }
         AppMemberVo user = loginUser.getUser();
         if (user == null) {
-            ServletUtils.renderString(httpServletResponse, JSON.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED, "用户不存在,请重新登录")));
+            ServletUtils.renderString(httpServletResponse, JSON.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED, "未登陆,请先登录")));
             return false;
             //throw new RuntimeException("用户不存在,请重新登录");
         }

+ 173 - 0
ruoyi-app/src/main/java/com/ruoyi/app/util/ImageCompressUtil.java

@@ -0,0 +1,173 @@
+package com.ruoyi.app.util;
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.Image;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+import javax.imageio.ImageIO;
+
+/**
+ * 图片压缩
+ */
+public class ImageCompressUtil {
+    /**
+     * 根据设置的宽高等比例压缩图片文件<br>
+     * 先保存原文件,再压缩、上传
+     *
+     * @param oldFile 要进行压缩的文件
+     * @param newFile 新文件
+     * @return 返回压缩后的文件的全路径
+     */
+    public static String zipImageFile(File oldFile, File newFile) {
+        if (oldFile == null) {
+            return null;
+        }
+        try {
+            /** 对服务器上的临时文件进行处理 */
+            Image srcFile = ImageIO.read(oldFile);
+            int w = srcFile.getWidth(null);
+            int h = srcFile.getHeight(null);
+            int w1 = w;
+            int h1 = h;
+            //对于小400分辨率的图不压缩
+            if (w < 1000 && w > 400) {
+                w1 = (int) (w - w * 0.3);
+                h1 = (int) (h - h * 0.3);
+            }
+            if (w < 1600 && w > 1000) {
+                w1 = (int) (w - w * 0.45);
+                h1 = (int) (h - h * 0.45);
+            }
+            if (w < 2500 && w > 1600) {
+                w1 = (int) (w - w * 0.6);
+                h1 = (int) (h - h * 0.6);
+            }
+            if (w > 2500) {
+                w1 = (int) (w - w * 0.75);
+                h1 = (int) (h - h * 0.75);
+            }
+            String srcImgPath = newFile.getAbsoluteFile().toString();
+            String subfix = "jpg";
+            subfix = srcImgPath.substring(srcImgPath.lastIndexOf(".") + 1, srcImgPath.length());
+
+            BufferedImage buffImg = null;
+            if (subfix.equals("png")) {
+                buffImg = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_ARGB);
+            } else {
+                buffImg = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB);
+            }
+            Graphics2D graphics = buffImg.createGraphics();
+            graphics.setBackground(new Color(255, 255, 255));
+            graphics.setColor(new Color(255, 255, 255));
+            graphics.fillRect(0, 0, w1, h1);
+            graphics.drawImage(srcFile.getScaledInstance(w1, h1, Image.SCALE_SMOOTH), 0, 0, null);
+            ImageIO.write(buffImg, subfix, new File(srcImgPath));
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return newFile.getAbsolutePath();
+    }
+
+    /**
+     * 根据设置的宽高等比例压缩图片文件<br>
+     * 先保存原文件,再压缩、上传
+     *
+     * @param oldFile 要进行压缩的文件
+     * @param newFile 新文件
+     * @return 返回压缩后的文件的全路径
+     */
+    public static String zipImageFile(File oldFile, File newFile, double display) {
+        if (oldFile == null) {
+            return null;
+        }
+        try {
+            /** 对服务器上的临时文件进行处理 */
+            Image srcFile = ImageIO.read(oldFile);
+            int w = srcFile.getWidth(null);
+            int h = srcFile.getHeight(null);
+            int w1 = w;
+            int h1 = h;
+            w1 = (int) (w - w * display);
+            h1 = (int) (h - h * display);
+            String srcImgPath = newFile.getAbsoluteFile().toString();
+            String subfix = "jpg";
+            subfix = srcImgPath.substring(srcImgPath.lastIndexOf(".") + 1, srcImgPath.length());
+
+            BufferedImage buffImg = null;
+            if (subfix.equals("png")) {
+                buffImg = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_ARGB);
+            } else {
+                buffImg = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB);
+            }
+            Graphics2D graphics = buffImg.createGraphics();
+            graphics.setBackground(new Color(255, 255, 255));
+            graphics.setColor(new Color(255, 255, 255));
+            graphics.fillRect(0, 0, w1, h1);
+            graphics.drawImage(srcFile.getScaledInstance(w1, h1, Image.SCALE_SMOOTH), 0, 0, null);
+            ImageIO.write(buffImg, subfix, new File(srcImgPath));
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return newFile.getAbsolutePath();
+    }
+
+    /**
+     * 按设置的宽度高度压缩图片文件<br>
+     * 先保存原文件,再压缩、上传
+     *
+     * @param oldFile 要进行压缩的文件全路径
+     * @param newFile 新文件
+     * @param width   宽度
+     * @param height  高度
+     * @param quality 质量
+     * @return 返回压缩后的文件的全路径
+     */
+    public static String zipWidthHeightImageFile(File oldFile, File newFile, int width, int height, float quality) {
+        if (oldFile == null) {
+            return null;
+        }
+        String newImage = null;
+        try {
+            /** 对服务器上的临时文件进行处理 */
+            Image srcFile = ImageIO.read(oldFile);
+
+            String srcImgPath = newFile.getAbsoluteFile().toString();
+            System.out.println(srcImgPath);
+            String subfix = "jpg";
+            subfix = srcImgPath.substring(srcImgPath.lastIndexOf(".") + 1, srcImgPath.length());
+
+            BufferedImage buffImg = null;
+            if (subfix.equals("png")) {
+                buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
+            } else {
+                buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
+            }
+
+            Graphics2D graphics = buffImg.createGraphics();
+            graphics.setBackground(new Color(255, 255, 255));
+            graphics.setColor(new Color(255, 255, 255));
+            graphics.fillRect(0, 0, width, height);
+            graphics.drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
+
+            ImageIO.write(buffImg, subfix, new File(srcImgPath));
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return newImage;
+    }
+
+    public static void main(String[] args) {
+        String asd = "D:/lineage/AppUploadPath/profile/upload/054142ce-ebc2-4af3-a867-7fdc32f17d25.JPG";
+        System.out.println(asd.replace("/profile", ""));
+    }
+}

+ 36 - 6
ruoyi-common/src/main/java/com/ruoyi/common/utils/PushUtil.java

@@ -1,11 +1,15 @@
 package com.ruoyi.common.utils;
 
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
 import com.gexin.rp.sdk.base.IPushResult;
+import com.gexin.rp.sdk.base.impl.AppMessage;
 import com.gexin.rp.sdk.base.impl.ListMessage;
 import com.gexin.rp.sdk.base.impl.Target;
 import com.gexin.rp.sdk.exceptions.RequestException;
 import com.gexin.rp.sdk.http.IGtPush;
 import com.gexin.rp.sdk.template.NotificationTemplate;
+import com.gexin.rp.sdk.template.TransmissionTemplate;
 import com.gexin.rp.sdk.template.style.Style0;
 
 import java.util.ArrayList;
@@ -61,13 +65,37 @@ public class PushUtil {
         return false;
 
     }
+    public static void asd(){
+        IGtPush push = new IGtPush(host, appKey, masterSecret);
+
+        TransmissionTemplate t = new TransmissionTemplate();
+        t.setAppId(appId);
+        t.setAppkey(appKey);
+        t.setTransmissionContent("{title:\"标题\",content:\"内容\",payload:\"自定义数据\"}");
+        t.setTransmissionType(1);
+
+
+        List<String> appIds = new ArrayList<String>();
+        appIds.add(appId);
+
+        // 定义"AppMessage"类型消息对象,设置消息内容模板、发送的目标App列表、是否支持离线发送、以及离线消息有效期(单位毫秒)
+        AppMessage message = new AppMessage();
+        message.setData(t);
+        message.setAppIdList(appIds);
+        message.setOffline(true);
+        message.setOfflineExpireTime(1000 * 600);
+
+        IPushResult ret = push.pushMessageToApp(message);
+        System.out.println(ret.getResponse().toString());
+    }
 
     public static void main(String[] args) {
         List<String>list=new ArrayList<>();
+        list.add("88d26b3633ca7d622704b473f6331487");
         list.add("4c5889ce0d7594141127eacb697b8007");
-        list.add("42a9c3372a60f1ccffe639520b421b07");
-        boolean s = sendMessage("家族通知", "余震申请加入", list);
+        boolean s = sendMessage("家族通知", "余东申请加入", list);
         System.out.println("ssss:" + s);
+       ///asd();
     }
 
     private static NotificationTemplate getNotificationTemplate(String title, String text) {
@@ -76,6 +104,7 @@ public class PushUtil {
         template.setAppId(appId);
         template.setAppkey(appKey);
 
+
         Style0 style = new Style0();
         // 设置通知栏标题与内容
         style.setTitle(title);
@@ -84,13 +113,14 @@ public class PushUtil {
         style.setRing(true);
         style.setVibrate(true);
         style.setClearable(true);
-        style.setChannel("通知渠道id");
-        style.setChannelName("通知渠道名称");
         style.setChannelLevel(3); //设置通知渠道重要性
         template.setStyle(style);
 
-        template.setTransmissionType(1);  // 透传消息接受方式设置,1:立即启动APP,2:客户端收到消息后需要自行处理
-        template.setTransmissionContent("请输入您要透传的内容");
+        template.setTransmissionType(2);  // 透传消息接受方式设置,1:立即启动APP,2:客户端收到消息后需要自行处理
+        JSONObject obj=new JSONObject();
+        obj.put("title",title);
+        obj.put("text",text);
+        template.setTransmissionContent(obj.toJSONString());
 
         return template;
     }