From bf3dcc63f2884284e2ea195b0a6307734f9d4c52 Mon Sep 17 00:00:00 2001
From: 龚焕茏 <2842157468@qq.com>
Date: 星期三, 12 六月 2024 15:46:50 +0800
Subject: [PATCH] feat:本地文件上传、预览

---
 src/main/java/com/ycl/jxkg/config/spring/mvc/WebMvcConfiguration.java |    8 +
 src/main/java/com/ycl/jxkg/config/RuoYiConfig.java                    |   64 ++++++++++++
 src/main/java/com/ycl/jxkg/controller/admin/UploadController.java     |   63 +++++++++---
 src/main/java/com/ycl/jxkg/controller/common/UploadController.java    |   95 +++++++++++++++++++
 src/main/resources/application-dev.yml                                |    4 
 src/main/resources/application-prod.yml                               |    4 
 src/main/resources/mapper/ExamPaperAnswerMapper.xml                   |    1 
 src/main/resources/application.yml                                    |    5 +
 8 files changed, 225 insertions(+), 19 deletions(-)

diff --git a/src/main/java/com/ycl/jxkg/config/RuoYiConfig.java b/src/main/java/com/ycl/jxkg/config/RuoYiConfig.java
new file mode 100644
index 0000000..553fff9
--- /dev/null
+++ b/src/main/java/com/ycl/jxkg/config/RuoYiConfig.java
@@ -0,0 +1,64 @@
+package com.ycl.jxkg.config;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+/**
+ * 璇诲彇椤圭洰鐩稿叧閰嶇疆
+ *
+ * @author ruoyi
+ */
+@Component
+@ConfigurationProperties(prefix = "upload")
+public class RuoYiConfig
+{
+
+    /** 涓婁紶璺緞 */
+    private String url;
+
+    public String getUrl() {
+        return url;
+    }
+
+    public void setUrl(String url) {
+        this.url = url;
+    }
+
+    public void setProfile(String profile)
+    {
+        url = profile;
+    }
+
+
+    /**
+     * 鑾峰彇瀵煎叆涓婁紶璺緞
+     */
+    public String getImportPath()
+    {
+        return url + "/import";
+    }
+
+    /**
+     * 鑾峰彇澶村儚涓婁紶璺緞
+     */
+    public String getAvatarPath()
+    {
+        return url + "/avatar";
+    }
+
+    /**
+     * 鑾峰彇涓嬭浇璺緞
+     */
+    public String getDownloadPath()
+    {
+        return url + "/download/";
+    }
+
+    /**
+     * 鑾峰彇涓婁紶璺緞
+     */
+    public String getUploadPath()
+    {
+        return url + "/upload";
+    }
+}
diff --git a/src/main/java/com/ycl/jxkg/config/spring/mvc/WebMvcConfiguration.java b/src/main/java/com/ycl/jxkg/config/spring/mvc/WebMvcConfiguration.java
index 45269a9..9100e60 100644
--- a/src/main/java/com/ycl/jxkg/config/spring/mvc/WebMvcConfiguration.java
+++ b/src/main/java/com/ycl/jxkg/config/spring/mvc/WebMvcConfiguration.java
@@ -1,11 +1,13 @@
 package com.ycl.jxkg.config.spring.mvc;
 
+import com.ycl.jxkg.config.RuoYiConfig;
 import com.ycl.jxkg.config.property.SystemConfig;
 import com.ycl.jxkg.config.spring.wx.TokenHandlerInterceptor;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.web.servlet.config.annotation.*;
 
+import java.io.File;
 import java.util.List;
 
 
@@ -20,6 +22,7 @@
 
     private final TokenHandlerInterceptor tokenHandlerInterceptor;
     private final SystemConfig systemConfig;
+    private final RuoYiConfig ruoYiConfig;
 
     /**
      * Instantiates a new Web mvc configuration.
@@ -28,9 +31,10 @@
      * @param systemConfig            the system config
      */
     @Autowired
-    public WebMvcConfiguration(TokenHandlerInterceptor tokenHandlerInterceptor, SystemConfig systemConfig) {
+    public WebMvcConfiguration(TokenHandlerInterceptor tokenHandlerInterceptor, SystemConfig systemConfig, RuoYiConfig ruoYiConfig) {
         this.tokenHandlerInterceptor = tokenHandlerInterceptor;
         this.systemConfig = systemConfig;
+        this.ruoYiConfig = ruoYiConfig;
     }
 
     @Override
@@ -42,6 +46,8 @@
 
     @Override
     public void addResourceHandlers(ResourceHandlerRegistry registry) {
+        registry.addResourceHandler("/api/files" + "/**")
+                .addResourceLocations("file:" + ruoYiConfig.getUrl() + File.separator);
         registry.addResourceHandler("/**")
                 .addResourceLocations("classpath:/static/")
                 .setCachePeriod(31556926);
diff --git a/src/main/java/com/ycl/jxkg/controller/admin/UploadController.java b/src/main/java/com/ycl/jxkg/controller/admin/UploadController.java
index 1a26b9b..6614268 100644
--- a/src/main/java/com/ycl/jxkg/controller/admin/UploadController.java
+++ b/src/main/java/com/ycl/jxkg/controller/admin/UploadController.java
@@ -3,23 +3,30 @@
 
 import com.ycl.jxkg.base.BaseApiController;
 import com.ycl.jxkg.base.Result;
+import com.ycl.jxkg.config.RuoYiConfig;
 import com.ycl.jxkg.config.property.SystemConfig;
-import com.ycl.jxkg.service.FileUpload;
-import com.ycl.jxkg.service.UserService;
 import com.ycl.jxkg.domain.vo.admin.file.UeditorConfigVO;
 import com.ycl.jxkg.domain.vo.admin.file.UploadResultVO;
+import com.ycl.jxkg.service.FileUpload;
+import com.ycl.jxkg.service.UserService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.util.StringUtils;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.multipart.MultipartFile;
 import org.springframework.web.multipart.MultipartHttpServletRequest;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.Arrays;
+import java.util.HashMap;
+import java.util.UUID;
 
 
 @RequestMapping("/api/admin/upload")
@@ -32,12 +39,14 @@
     private static final String IMAGE_UPLOAD = "imgUpload";
     private static final String IMAGE_UPLOAD_FILE = "upFile";
     private final UserService userService;
+    private final RuoYiConfig ruoYiConfig;
 
     @Autowired
-    public UploadController(FileUpload fileUpload, SystemConfig systemConfig, UserService userService) {
+    public UploadController(FileUpload fileUpload, SystemConfig systemConfig, UserService userService, RuoYiConfig ruoYiConfig) {
         this.fileUpload = fileUpload;
         this.systemConfig = systemConfig;
         this.userService = userService;
+        this.ruoYiConfig = ruoYiConfig;
     }
 
     @ResponseBody
@@ -45,26 +54,45 @@
     public Object upload(HttpServletRequest request, HttpServletResponse response) {
         String action = request.getParameter("action");
         if (action.equals(IMAGE_UPLOAD)) {
+            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
+            MultipartFile file = multipartHttpServletRequest.getFile(IMAGE_UPLOAD_FILE);
+            // 妫�鏌ユ枃浠舵槸鍚︿负绌�
+            if (file.isEmpty()) {
+                return Result.fail(500, "涓婁紶鐨勬枃浠朵负绌�");
+            }
             try {
-                MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
-                MultipartFile multipartFile = multipartHttpServletRequest.getFile(IMAGE_UPLOAD_FILE);
-                long attachSize = multipartFile.getSize();
-                String imgName = multipartFile.getOriginalFilename();
-                String filePath;
-                try (InputStream inputStream = multipartFile.getInputStream()) {
-                    filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
+                // 鑾峰彇鏂囦欢鍚�
+                String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
+                String randomName = UUID.randomUUID().toString().replace("-", "") + originalFileName.substring(originalFileName.lastIndexOf("."));
+                // 鎸囧畾鏂囦欢瀛樺偍璺緞
+                String uploadDir = ruoYiConfig.getUrl(); // 淇敼涓烘偍甯屾湜瀛樺偍鐨勭洰褰�
+                // 濡傛灉鐩綍涓嶅瓨鍦紝鍒欏垱寤虹洰褰�
+                File dir = new File(uploadDir);
+                if (!dir.exists()) {
+                    dir.mkdirs();
                 }
-                String imageType = imgName.substring(imgName.lastIndexOf("."));
+                // 鏋勫缓鐩爣鏂囦欢鐨勮矾寰�
+                String filePath = uploadDir + "/" + randomName;
+                // 灏嗘枃浠朵繚瀛樺埌鐩爣浣嶇疆
+                file.transferTo(new File(filePath));
+                // 杩斿洖鎴愬姛鍝嶅簲
+                HashMap hashMap = new HashMap(2);
+                hashMap.put("name", originalFileName);
+                hashMap.put("url", randomName);
+
+                String imageType = randomName.substring(randomName.lastIndexOf("."));
                 UploadResultVO uploadResultVO = new UploadResultVO();
-                uploadResultVO.setOriginal(imgName);
-                uploadResultVO.setName(imgName);
-                uploadResultVO.setUrl(filePath);
-                uploadResultVO.setSize(multipartFile.getSize());
+                uploadResultVO.setOriginal(randomName);
+                uploadResultVO.setName(randomName);
+                uploadResultVO.setUrl("/api/files/" + randomName);
+                uploadResultVO.setSize(10L);
                 uploadResultVO.setType(imageType);
                 uploadResultVO.setState("SUCCESS");
                 return uploadResultVO;
             } catch (IOException e) {
-                logger.error(e.getMessage(), e);
+                e.printStackTrace();
+                // 杩斿洖澶辫触鍝嶅簲
+                return Result.fail(500, "鏂囦欢涓婁紶澶辫触");
             }
         } else {
             UeditorConfigVO ueditorConfigVO = new UeditorConfigVO();
@@ -79,7 +107,6 @@
             ueditorConfigVO.setImagePathFormat("");
             return ueditorConfigVO;
         }
-        return null;
     }
 
 
diff --git a/src/main/java/com/ycl/jxkg/controller/common/UploadController.java b/src/main/java/com/ycl/jxkg/controller/common/UploadController.java
new file mode 100644
index 0000000..e8cd1a8
--- /dev/null
+++ b/src/main/java/com/ycl/jxkg/controller/common/UploadController.java
@@ -0,0 +1,95 @@
+package com.ycl.jxkg.controller.common;
+
+import com.ycl.jxkg.base.Result;
+import com.ycl.jxkg.config.RuoYiConfig;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.MediaType;
+import org.springframework.util.StringUtils;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.HashMap;
+import java.util.UUID;
+
+/**
+ * @author锛歺p
+ * @date锛�2024/5/15 17:02
+ */
+
+@RestController
+@RequiredArgsConstructor
+@RequestMapping("/api/upload")
+public class UploadController {
+
+    private final RuoYiConfig ruoYiConfig;
+
+    /**
+     * 閫氱敤涓婁紶璇锋眰锛堝崟涓級
+     */
+    @PostMapping("/upload")
+    public Result uploadFile(MultipartFile file) throws Exception
+    {
+        // 妫�鏌ユ枃浠舵槸鍚︿负绌�
+        if (file.isEmpty()) {
+            return Result.fail(500, "涓婁紶鐨勬枃浠朵负绌�");
+        }
+        try {
+            // 鑾峰彇鏂囦欢鍚�
+            String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
+            String randomName = UUID.randomUUID().toString().replace("-", "") + originalFileName.substring(originalFileName.lastIndexOf("."));
+            // 鎸囧畾鏂囦欢瀛樺偍璺緞
+            String uploadDir = ruoYiConfig.getUrl(); // 淇敼涓烘偍甯屾湜瀛樺偍鐨勭洰褰�
+            // 濡傛灉鐩綍涓嶅瓨鍦紝鍒欏垱寤虹洰褰�
+            File dir = new File(uploadDir);
+            if (!dir.exists()) {
+                dir.mkdirs();
+            }
+            // 鏋勫缓鐩爣鏂囦欢鐨勮矾寰�
+            String filePath = uploadDir + "/" + randomName;
+            // 灏嗘枃浠朵繚瀛樺埌鐩爣浣嶇疆
+            file.transferTo(new File(filePath));
+            // 杩斿洖鎴愬姛鍝嶅簲
+            HashMap hashMap = new HashMap(2);
+            hashMap.put("name", originalFileName);
+            hashMap.put("url", randomName);
+            return Result.ok(hashMap);
+        } catch (IOException e) {
+            e.printStackTrace();
+            // 杩斿洖澶辫触鍝嶅簲
+            return Result.fail(500, "鏂囦欢涓婁紶澶辫触");
+        }
+    }
+
+    /**
+     * 涓嬭浇鏂囦欢锛堝崟涓級
+     */
+    @GetMapping("/download")
+    public void download(@RequestParam String url, @RequestParam String fileName, HttpServletResponse response) throws Exception
+    {
+        // 鎻愬彇鏂囦欢璺緞
+        String filePath = ruoYiConfig.getUrl() + File.separator + url;
+
+        File file = new File(filePath);
+
+        // 妫�鏌ユ枃浠舵槸鍚﹀瓨鍦�
+        if (!file.exists()) {
+            throw new RuntimeException("鏂囦欢涓嶅瓨鍦�");
+        }
+
+        // 璇诲彇鏂囦欢鍐呭
+        byte[] fileContent = Files.readAllBytes(file.toPath());
+
+        // 璁剧疆鍝嶅簲澶�
+        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
+        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
+
+        // 灏嗘枃浠跺唴瀹瑰啓鍏ュ搷搴旇緭鍑烘祦
+        response.getOutputStream().write(fileContent);
+        response.getOutputStream().flush();
+    }
+
+}
diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml
index 26b040a..982aa58 100644
--- a/src/main/resources/application-dev.yml
+++ b/src/main/resources/application-dev.yml
@@ -1,6 +1,10 @@
 logging:
   path: ./log/
 
+upload:
+  # 鏂囦欢璺緞 绀轰緥锛� Windows閰嶇疆D:/ruoyi/uploadPath锛孡inux閰嶇疆 /home/ruoyi/uploadPath锛�
+  url: E:/ycl/file
+
 spring:
   datasource:
     url: jdbc:mysql://42.193.1.25:3306/xzs?useSSL=false&useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&allowMultiQueries=true
diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml
index 1f9d678..3e03604 100644
--- a/src/main/resources/application-prod.yml
+++ b/src/main/resources/application-prod.yml
@@ -1,6 +1,10 @@
 logging:
   path: /usr/log/xzs/
 
+upload:
+  # 鏂囦欢璺緞 绀轰緥锛� Windows閰嶇疆D:/ruoyi/uploadPath锛孡inux閰嶇疆 /home/ruoyi/uploadPath锛�
+  url: /usr/local/file
+
 spring:
   datasource:
     url: jdbc:mysql://localhost:3306/xzs?useSSL=false&useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&allowMultiQueries=true
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 6a75cdc..2e98aaa 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -70,6 +70,11 @@
     hikari:
       idle-timeout: 600000  #10 min
       max-lifetime: 1800000 #30 min
+  servlet:
+    multipart:
+      max-file-size: 50MB
+      max-request-size: 500MB
+
   #runningtime environment
   profiles:
     active: dev
diff --git a/src/main/resources/mapper/ExamPaperAnswerMapper.xml b/src/main/resources/mapper/ExamPaperAnswerMapper.xml
index 7a18975..9ae525b 100644
--- a/src/main/resources/mapper/ExamPaperAnswerMapper.xml
+++ b/src/main/resources/mapper/ExamPaperAnswerMapper.xml
@@ -71,6 +71,7 @@
         question_correct, question_count, do_time, a.status, create_user, a.create_time, b.real_name AS userName
         FROM t_exam_paper_answer a
         LEFT JOIN t_user b ON a.create_user = b.id
+        INNER JOIN t.exam c ON a.exam_paper_id = c.exam_paper_id AND c.status = 'finished'
         <where>
             <if test="examPaperId != null">
                 AND exam_paper_id = #{examPaperId}

--
Gitblit v1.8.0