瀏覽代碼

重构上传下载

Danj0rr 11 月之前
父節點
當前提交
1d0890f765
共有 1 個文件被更改,包括 72 次插入18 次删除
  1. 72 18
      src/main/java/com/kexun/controller/FileUploadController.java

+ 72 - 18
src/main/java/com/kexun/controller/FileUploadController.java

@@ -1,5 +1,7 @@
 package com.kexun.controller;
 
+import com.kexun.entity.ReportFileEntity;
+import com.kexun.enums.FileTypeEnum;
 import net.coobird.thumbnailator.Thumbnails;
 import org.springframework.core.io.FileSystemResource;
 import com.alibaba.fastjson.JSONObject;
@@ -18,6 +20,8 @@ import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.nio.file.Files;
 import java.util.Base64;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
 
 import org.springframework.util.StringUtils;
 import org.springframework.http.HttpHeaders;
@@ -32,7 +36,7 @@ import com.kexun.entity.SysUser;
 import com.kexun.entity.UserApproval;
 import com.kexun.service.UserApprovalService;
 import com.kexun.service.UserModelService;
-import lombok.extern.java.Log;
+import lombok.extern.slf4j.Slf4j;
 //import org.aspectj.util.FileUtil;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
@@ -59,7 +63,7 @@ import javax.swing.filechooser.FileSystemView;
 
 @RestController
 @RequestMapping("/admin/othermodel")
-@Log
+@Slf4j
 public class FileUploadController {
     @Autowired
     private UserModelService userModelService;
@@ -75,28 +79,78 @@ public class FileUploadController {
 
 
     @GetMapping("/download/{filename}")
-    public Result downloadFile(@PathVariable("filename") String filename, SysUser sysUser) throws IOException {
-        String filePath = fileuploadPath + sysUser.getUserName() + '/' + filename; // 设置文件路径
-        File file = new File(filePath);
-
-        if (file.exists()) {
-            byte[] fileContent = Files.readAllBytes(file.toPath());
-            String base64 = Base64.getEncoder().encodeToString(fileContent);
-            JSONObject resJson = new JSONObject();
-            resJson.put("file", base64);
-            return Result.success("ok", resJson);
-        } else {
-            return Result.error("文件不存在!");
+    public void downloadFile(HttpServletResponse response, @PathVariable("filename") String filename, SysUser sysUser) throws IOException {
+        File zipFile = new File(System.currentTimeMillis() + ".zip");
+        ZipOutputStream zipOutputStream = null;
+        try {
+            zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));
+
+            String filePath = fileuploadPath + sysUser.getUserName() + '/' + filename; // 设置文件路径
+            File file = new File(filePath);
+            if (file.exists()) {
+                byte[] bytes = new byte[4096];
+                ZipEntry entry = new ZipEntry(file.getName());
+                zipOutputStream.putNextEntry(entry);
+                FileInputStream fileInputStream = new FileInputStream(file);
+                int length;
+                while ((length = fileInputStream.read(bytes)) > 0) {
+                    zipOutputStream.write(bytes, 0, length);
+                }
+                zipOutputStream.closeEntry();
+                fileInputStream.close();
+            } else {
+                log.error("文件找不到,所在路径为{}", filePath);
+            }
+
+            //注意,这行代码不能放到下一行代码之后,否则最后一个写入的文件会为空
+            zipOutputStream.close();
+            byte[] bytes = Files.readAllBytes(zipFile.toPath());
+            zipFile.delete();
+            response.setContentType("application/octet-stream; charset=utf-8");
+            response.setCharacterEncoding("utf8");
+            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8"));
+            response.setHeader("Pragma", "public");
+            response.setHeader("Cache-Control", "no-store");
+            response.addHeader("Cache-Control", "max-age=0");
+            OutputStream outputStream = response.getOutputStream();
+            outputStream.write(bytes);
+            response.flushBuffer();
+        } catch (Exception e) {
+            e.printStackTrace();
         }
 
     }
 
+//    @GetMapping("/download/{filename}")
+//    public Result downloadFile(@PathVariable("filename") String filename, SysUser sysUser) throws IOException {
+//        String filePath = fileuploadPath + sysUser.getUserName() + '/' + filename; // 设置文件路径
+//        File file = new File(filePath);
+//
+//        if (file.exists()) {
+//            byte[] fileContent = Files.readAllBytes(file.toPath());
+//            String base64 = Base64.getEncoder().encodeToString(fileContent);
+//            JSONObject resJson = new JSONObject();
+//            resJson.put("file", base64);
+//            return Result.success("ok", resJson);
+//        } else {
+//            return Result.error("文件不存在!");
+//        }
+//
+//    }
+
     @PostMapping("/filechange")
     public Result filechange(@RequestParam Integer index, @RequestParam MultipartFile chunk, @RequestParam String name, @RequestParam Integer chunksLength, @RequestParam String uid
             , @RequestParam String output_list, SysUser sysUser, @RequestParam long id
     ) throws IOException {
-        String filename = name.split("\\.")[0];
-        String filefmt = name.split("\\.")[1];
+        String filename = "";
+        String filefmt = "";
+        int lastDotIndex = name.lastIndexOf(".");
+        if (lastDotIndex != -1 && lastDotIndex < name.length() - 1) {
+            filename = name.substring(0, lastDotIndex);
+            filefmt = name.substring(lastDotIndex + 1);
+        } else {
+            return Result.error("文件名中不包含点或点在末尾");
+        }
         String fullFileName = String.join("-", new String[]{filename, uid, index + "", "." + filefmt});
         String filePath = fileuploadPath + "/" + sysUser.getUserName() + "/" + filename + "." + filefmt;
         log.info("filename:" + fullFileName);
@@ -152,8 +206,8 @@ public class FileUploadController {
     ) throws IOException {
         int type = Integer.parseInt(model_type);
 
-        String filename="";
-        String filefmt="";
+        String filename = "";
+        String filefmt = "";
         int lastDotIndex = name.lastIndexOf(".");
         if (lastDotIndex != -1 && lastDotIndex < name.length() - 1) {
             filename = name.substring(0, lastDotIndex);