From 8eaf1be9979c6dc210c7794728a2c59e6eec9abd Mon Sep 17 00:00:00 2001
From: 13693261870 <252740454@qq.com>
Date: 星期五, 14 十月 2022 14:54:58 +0800
Subject: [PATCH] 1

---
 src/main/java/com/lf/server/service/all/FileService.java |  151 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 149 insertions(+), 2 deletions(-)

diff --git a/src/main/java/com/lf/server/service/all/FileService.java b/src/main/java/com/lf/server/service/all/FileService.java
index c4973fa..a5d28e2 100644
--- a/src/main/java/com/lf/server/service/all/FileService.java
+++ b/src/main/java/com/lf/server/service/all/FileService.java
@@ -1,17 +1,36 @@
 package com.lf.server.service.all;
 
+import com.alibaba.fastjson.JSON;
+import com.lf.server.controller.all.BaseController;
+import com.lf.server.entity.all.HttpStatus;
+import com.lf.server.entity.all.ResponseMsg;
+import com.lf.server.entity.all.SettingData;
+import com.lf.server.entity.sys.AttachEntity;
+import com.lf.server.entity.sys.UserEntity;
+import com.lf.server.helper.FileHelper;
+import com.lf.server.helper.PathHelper;
+import com.lf.server.helper.StringHelper;
+import com.lf.server.helper.WebHelper;
+import com.lf.server.service.sys.AttachService;
+import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.tomcat.util.http.fileupload.FileItem;
 import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
 import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
 import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
 
 import javax.servlet.ServletContext;
+import javax.servlet.ServletOutputStream;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.URLEncoder;
 import java.util.List;
 import java.util.UUID;
 
@@ -21,7 +40,135 @@
  */
 @Service
 public class FileService {
+    @Autowired
+    PathHelper pathHelper;
+
+    @Autowired
+    AttachService attachService;
+
     private final static Log log = LogFactory.getLog(FileService.class);
+
+    private static final String NO_FILE = JSON.toJSONString(new ResponseMsg<String>(HttpStatus.NOT_FOUND, "鏂囦欢鎵句笉鍒�"));
+
+    /**
+     * 涓婁紶鏂囦欢
+     */
+    public ResponseMsg<String> upload(UserEntity ue, String tab, MultipartFile file, BaseController ctrl) {
+        try {
+            if (file == null && file.isEmpty()) {
+                return ctrl.fail("鏂囦欢涓婁紶涓虹┖", null);
+            }
+            if (file.getSize() > SettingData.MAX_FILE_SIZE) {
+                return ctrl.fail(String.format("鏂囦欢澶т簬 %d MB", SettingData.MAX_FILE_SIZE / 1024 / 1024), null);
+            }
+
+            // 浼犺緭鏂囦欢
+            String oldName = file.getOriginalFilename();
+            String filePath = pathHelper.getConfig().getTempPath() + File.separator + oldName;
+            File newFile = new File(filePath);
+            file.transferTo(newFile);
+
+            // 鑾峰彇MD5
+            String md5 = getFileMd5(filePath);
+            AttachEntity entity = attachService.selectByGuid(md5);
+            if (entity != null) {
+                newFile.delete();
+                return ctrl.success("鏂囦欢宸插瓨鍦�", md5);
+            }
+
+            AttachEntity ae = getAttachEntity(ue, tab, oldName, md5);
+            String targetPath = pathHelper.getConfig().getUploadPath() + File.separator + ae.getPath();
+            newFile.renameTo(new File(targetPath));
+
+            int rows = attachService.insert(ae);
+
+            return rows > 0 ? ctrl.success(md5) : ctrl.fail("淇濆瓨鏂囦欢澶辫触", null);
+        } catch (Exception ex) {
+            return ctrl.fail(ex.getMessage(), null);
+        }
+    }
+
+    private String getFileMd5(String filePath) throws IOException {
+        FileInputStream fileStream = new FileInputStream(filePath);
+        String md5 = DigestUtils.md5Hex(fileStream);
+        fileStream.close();
+
+        return md5;
+    }
+
+    protected AttachEntity getAttachEntity(UserEntity ue, String tab, String oldName, String md5) {
+        AttachEntity entity = new AttachEntity();
+        entity.setName(oldName);
+        entity.setTab(tab);
+        entity.setGuid(md5);
+        String subPath = PathHelper.getUploadPath() + File.separator + md5;
+        entity.setPath(subPath);
+        if (ue != null) {
+            entity.setCreateUser(ue.getId());
+        }
+
+        return entity;
+    }
+
+    /**
+     * 涓嬭浇鏂囦欢
+     */
+    public void download(String guid, HttpServletRequest req, HttpServletResponse res, BaseController ctrl) {
+        try {
+            if (StringHelper.isEmpty(guid)) {
+                WebHelper.write2Page(res, NO_FILE);
+                return;
+            }
+
+            AttachEntity entity = attachService.selectByGuid(guid);
+            if (entity == null) {
+                WebHelper.write2Page(res, NO_FILE);
+                return;
+            }
+
+            setDownloadResponse(entity, res);
+            String filePath = pathHelper.getConfig().getUploadPath() + File.separator + entity.getPath();
+
+            // 閫氳繃response瀵硅薄锛岃幏鍙栧埌杈撳嚭娴�
+            ServletOutputStream outputStream = res.getOutputStream();
+            // 瀹氫箟杈撳叆娴侊紝閫氳繃杈撳叆娴佽鍙栨枃浠跺唴瀹�
+            FileInputStream fileInputStream = new FileInputStream(filePath);
+
+            int len = 0;
+            byte[] bytes = new byte[1024];
+            while ((len = fileInputStream.read(bytes)) != -1) {
+                // 閫氳繃杈撳叆娴佽鍙栨枃浠舵暟鎹紝鐒跺悗閫氳繃涓婅堪鐨勮緭鍑烘祦鍐欏洖娴忚鍣�
+                outputStream.write(bytes, 0, len);
+                outputStream.flush();
+            }
+
+            // 鍏抽棴璧勬簮
+            outputStream.close();
+            fileInputStream.close();
+        } catch (Exception ex) {
+            try {
+                String msg = JSON.toJSONString(new ResponseMsg<String>(HttpStatus.ERROR, "鏂囦欢涓嬭浇鍑洪敊"));
+                WebHelper.write2Page(res, msg);
+            } catch (Exception e) {
+                log.error(e.getMessage() + e.getStackTrace() + "\n");
+            }
+            log.error(ex.getMessage() + ex.getStackTrace() + "\n");
+        }
+    }
+
+    private void setDownloadResponse(AttachEntity entity, HttpServletResponse res) throws IOException {
+        String fileName = URLEncoder.encode(entity.getName(), "UTF-8");
+
+        // 璁剧疆鍝嶅簲澶翠腑鏂囦欢鐨勪笅杞芥柟寮忎负闄勪欢鏂瑰紡锛屼互鍙婅缃枃浠跺悕
+        res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
+        // 璁剧疆鍝嶅簲澶寸殑缂栫爜鏍煎紡涓篣TF-8
+        res.setCharacterEncoding("UTF-8");
+
+        // 閫氳繃response瀵硅薄璁剧疆鍝嶅簲鏁版嵁鏍煎紡(濡傦細"text/plain; charset=utf-8")
+        String ext = FileHelper.getExtension(entity.getName());
+        String mime = FileHelper.getMime(ext);
+        res.setContentType(mime);
+    }
 
     /**
      * 涓婁紶鏂囦欢
@@ -66,7 +213,7 @@
                 }
             }
         } catch (Exception ex) {
-            log.error(ex.getStackTrace());
+            log.error(ex.getMessage() + ex.getStackTrace() + "\n");
         }
     }
 
@@ -85,7 +232,7 @@
             // 浠� utf-8鐨勭紪鐮佹牸寮忔潵瑙f瀽 value鍊�
             value = item.getString("utf-8");
         } catch (Exception ex) {
-            log.error(ex.getStackTrace());
+            log.error(ex.getMessage() + ex.getStackTrace() + "\n");
         }
 
         // 杈撳嚭鍒版帶鍒跺彴

--
Gitblit v1.9.3