Explorar el Código

feat:下载工程文件逻辑更改

韩帛霖 hace 1 año
padre
commit
87d2c02a12

+ 98 - 36
zkqy-admin/src/main/java/com/zkqy/web/controller/system/SysEngineeringController.java

@@ -5,9 +5,7 @@ import java.nio.file.DirectoryStream;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
-import java.time.Instant;
 import java.util.*;
-import java.util.stream.Collectors;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipOutputStream;
 import javax.servlet.http.HttpServletResponse;
@@ -17,12 +15,8 @@ import com.zkqy.common.core.domain.entity.DataSource;
 import com.zkqy.common.core.domain.entity.SysUser;
 import com.zkqy.common.utils.DateUtils;
 import com.zkqy.common.utils.SecurityUtils;
-import io.swagger.annotations.Api;
+import com.zkqy.common.utils.file.ZipUtils;
 import io.swagger.annotations.ApiOperation;
-import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
-import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
-import org.apache.commons.compress.utils.IOUtils;
-import org.springframework.core.io.InputStreamResource;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.http.ResponseEntity;
@@ -54,19 +48,17 @@ import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBo
  */
 @RestController
 @RequestMapping("/system/engineering")
-public class SysEngineeringController extends BaseController
-{
+public class SysEngineeringController extends BaseController {
     @Autowired
     private ISysEngineeringService sysEngineeringService;
 
-/**
- * 查询工程部署列表
- */
-@PreAuthorize("@ss.hasPermi('system:engineering:list')")
-@GetMapping("/list")
-@ApiOperation(value = "查询工程部署列表")
-    public TableDataInfo list(SysEngineering sysEngineering)
-    {
+    /**
+     * 查询工程部署列表
+     */
+    @PreAuthorize("@ss.hasPermi('system:engineering:list')")
+    @GetMapping("/list")
+    @ApiOperation(value = "查询工程部署列表")
+    public TableDataInfo list(SysEngineering sysEngineering) {
         startPage();
         List<SysEngineering> list = sysEngineeringService.selectSysEngineeringList(sysEngineering);
         return getDataTable(list);
@@ -79,8 +71,7 @@ public class SysEngineeringController extends BaseController
     @Log(title = "工程部署", businessType = BusinessType.EXPORT)
     @PostMapping("/export")
     @ApiOperation(value = "导出工程部署列表")
-    public void export(HttpServletResponse response, SysEngineering sysEngineering)
-    {
+    public void export(HttpServletResponse response, SysEngineering sysEngineering) {
         List<SysEngineering> list = sysEngineeringService.selectSysEngineeringList(sysEngineering);
         ExcelUtil<SysEngineering> util = new ExcelUtil<SysEngineering>(SysEngineering.class);
         util.exportExcel(response, list, "工程部署数据");
@@ -92,8 +83,7 @@ public class SysEngineeringController extends BaseController
     @PreAuthorize("@ss.hasPermi('system:engineering:query')")
     @GetMapping(value = "/{id}")
     @ApiOperation(value = "获取工程部署详细信息")
-    public AjaxResult getInfo(@PathVariable("id") Long id)
-    {
+    public AjaxResult getInfo(@PathVariable("id") Long id) {
         return success(sysEngineeringService.selectSysEngineeringById(id));
     }
 
@@ -104,8 +94,7 @@ public class SysEngineeringController extends BaseController
     @Log(title = "工程部署", businessType = BusinessType.INSERT)
     @PostMapping
     @ApiOperation(value = "新增工程部署")
-    public AjaxResult add(@RequestBody SysEngineering sysEngineering)
-    {
+    public AjaxResult add(@RequestBody SysEngineering sysEngineering) {
         return toAjax(sysEngineeringService.insertSysEngineering(sysEngineering));
     }
 
@@ -116,8 +105,7 @@ public class SysEngineeringController extends BaseController
     @Log(title = "工程部署", businessType = BusinessType.UPDATE)
     @PutMapping
     @ApiOperation(value = "修改工程部署")
-    public AjaxResult edit(@RequestBody SysEngineering sysEngineering)
-    {
+    public AjaxResult edit(@RequestBody SysEngineering sysEngineering) {
         return toAjax(sysEngineeringService.updateSysEngineering(sysEngineering));
     }
 
@@ -128,8 +116,7 @@ public class SysEngineeringController extends BaseController
     @Log(title = "工程部署", businessType = BusinessType.DELETE)
     @DeleteMapping("/{ids}")
     @ApiOperation(value = "删除工程部署")
-    public AjaxResult remove(@PathVariable Long[] ids)
-    {
+    public AjaxResult remove(@PathVariable Long[] ids) {
         return toAjax(sysEngineeringService.deleteSysEngineeringByIds(ids));
     }
 
@@ -144,7 +131,7 @@ public class SysEngineeringController extends BaseController
 
         File dir = new File(sourceFilePath);
         // 判断文件夹路径是否存在,不存在创建
-        if (!dir.exists()){
+        if (!dir.exists()) {
             boolean isCreated = dir.mkdirs();
             if (!isCreated) {
                 System.out.println("目录 '" + sourceFilePath + "' 创建失败.");
@@ -160,7 +147,7 @@ public class SysEngineeringController extends BaseController
 //        databaseList.add("zkqy-call");
         databaseList.add(datasourceInfo.getDatabaseName());
         //将sql文件导出到指定目录下
-        exportMultipleDatabasesToLocal(databaseList,sourceFilePath,datasourceInfo);
+        exportMultipleDatabasesToLocal(databaseList, sourceFilePath, datasourceInfo);
 
         //下载成功插入数据
         SysUser sysUser = SecurityUtils.getLoginUser().getUser();
@@ -170,7 +157,7 @@ public class SysEngineeringController extends BaseController
         sysEngineering.setEngineeringName(sysUser.getTenantName() + "-mes");
         sysEngineeringService.insertSysEngineering(sysEngineering);
 
-        String zipFileName = new Date().getTime()+".zip";
+        String zipFileName = new Date().getTime() + ".zip";
         HttpHeaders headers = new HttpHeaders();
         headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + zipFileName + "\"");
         headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
@@ -191,6 +178,45 @@ public class SysEngineeringController extends BaseController
 
     }
 
+    /**
+     * 下载压缩包
+     */
+    @GetMapping("/download1")
+    public void downloadZip1(HttpServletResponse response) {
+        // 指定要打包的文件或目录路径
+        String sourceFilePath = ZkqyConfig.getUploadPath() + "/engineeringdownload/";
+
+
+        File dir = new File(sourceFilePath);
+        // 判断文件夹路径是否存在,不存在创建
+        if (!dir.exists()) {
+            boolean isCreated = dir.mkdirs();
+            if (!isCreated) {
+                System.out.println("目录 '" + sourceFilePath + "' 创建失败.");
+            }
+        }
+
+
+        //当前用户数据源信息
+        DataSource datasourceInfo = SecurityUtils.getDatasourceInfo();
+        //导出数据库集合
+        Set<String> databaseList = new LinkedHashSet<>();
+        databaseList.add("ry-vue-call");
+        databaseList.add(datasourceInfo.getDatabaseName());
+        //将sql文件导出到指定目录下
+        exportMultipleDatabasesToLocal(databaseList, sourceFilePath, datasourceInfo);
+
+        //下载成功插入数据
+        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
+        SysEngineering sysEngineering = new SysEngineering();
+        sysEngineering.setCreateTime(DateUtils.getNowDate());
+        sysEngineering.setDownloadTime(DateUtils.getNowDate());
+        sysEngineering.setEngineeringName(sysUser.getTenantName() + "-mes");
+        sysEngineeringService.insertSysEngineering(sysEngineering);
+        List<Map<String, String>> fileList = listFiles(sourceFilePath);
+        ZipUtils.createZip(response, fileList);
+    }
+
     private void addFilesToZipRecursively(ZipOutputStream zipOut, Path rootPath, DirectoryStream<Path> dirStream) throws IOException {
         for (Path filePath : dirStream) {
             if (Files.isDirectory(filePath)) {
@@ -224,18 +250,18 @@ public class SysEngineeringController extends BaseController
     /**
      * 导出数据库文件
      */
-    public void exportMultipleDatabasesToLocal(Set<String> databaseNames, String outputPath, DataSource dataSource){
+    public void exportMultipleDatabasesToLocal(Set<String> databaseNames, String outputPath, DataSource dataSource) {
         outputPath = outputPath + "sql/";
 
         File dir = new File(outputPath);
         // 判断文件夹路径是否存在,不存在创建
-        if (!dir.exists()){
+        if (!dir.exists()) {
             boolean isCreated = dir.mkdirs();
             if (!isCreated) {
                 System.out.println("目录 '" + outputPath + "' 创建失败.");
             }
         }
-        for (String databaseName : databaseNames){
+        for (String databaseName : databaseNames) {
             try {
                 // 构建命令参数列表
                 List<String> cmd = new ArrayList<>();
@@ -250,14 +276,14 @@ public class SysEngineeringController extends BaseController
 
                 ProcessBuilder pb = new ProcessBuilder(cmd);
                 // 设置MySQL bin目录到PATH环境变量,确保mysqldump可执行文件能找到
-//                Map<String, String> env = pb.environment();
-//                env.put("PATH", env.get("PATH") + File.pathSeparator + "D:\\software\\installpath\\mysql-8.0.20\\mysql-8.0.20-winx64\\bin");
+                Map<String, String> env = pb.environment();
+                env.put("PATH", env.get("PATH") + File.pathSeparator + "\\usr\\local\\mysql\\bin");
 
                 // 创建进程并获取输出流
                 Process process = pb.start();
 
                 // 将mysqldump的输出重定向到文件
-                OutputStream outStream = new FileOutputStream(Paths.get(outputPath+databaseName+".sql").toFile());
+                OutputStream outStream = new FileOutputStream(Paths.get(outputPath + databaseName + ".sql").toFile());
                 InputStream processOutput = process.getInputStream();
                 byte[] buffer = new byte[4096];
                 int read;
@@ -291,4 +317,40 @@ public class SysEngineeringController extends BaseController
         }
     }
 
+    public static List<Map<String, String>> listFiles(String directoryPath) {
+        List<Map<String, String>> fileList = new ArrayList<>();
+        File directory = new File(directoryPath);
+
+        if (directory.exists() && directory.isDirectory()) {
+            listFilesRecursively(directory, fileList);
+        }
+
+        return fileList;
+    }
+
+    private static void listFilesRecursively(File directory, List<Map<String, String>> fileList) {
+        File[] files = directory.listFiles();
+
+        if (files != null) {
+            for (File file : files) {
+                if (file.isFile()) {
+                    Map<String, String> fileMap = new HashMap<>();
+                    fileMap.put("fileName", file.getName());
+                    fileMap.put("filePath", file.getAbsolutePath());
+                    fileList.add(fileMap);
+                } else if (file.isDirectory()) {
+                    listFilesRecursively(file, fileList);
+                }
+            }
+        }
+    }
+
+    public static void main(String[] args) {
+        String directoryPath = "/path/to/your/directory"; // 替换为你的文件夹路径
+        List<Map<String, String>> fileList = listFiles(directoryPath);
+
+        for (Map<String, String> fileMap : fileList) {
+            System.out.println("FileName: " + fileMap.get("fileName") + ", FilePath: " + fileMap.get("filePath"));
+        }
+    }
 }

+ 6 - 0
zkqy-common/pom.xml

@@ -138,6 +138,12 @@
             <artifactId>hutool-all</artifactId>
             <version>5.8.16</version>
         </dependency>
+        <!--Zip压缩-->
+        <dependency>
+            <groupId>org.apache.ant</groupId>
+            <artifactId>ant</artifactId>
+            <version>1.9.1</version>
+        </dependency>
     </dependencies>
 
 </project>

+ 57 - 0
zkqy-common/src/main/java/com/zkqy/common/utils/file/ZipUtils.java

@@ -0,0 +1,57 @@
+package com.zkqy.common.utils.file;
+
+
+import org.apache.tools.zip.ZipEntry;
+import org.apache.tools.zip.ZipOutputStream;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.List;
+import java.util.Map;
+
+public class ZipUtils {
+
+    /**
+     * 创建多文件压缩包
+     *
+     * @param response
+     *
+     * @param fileList  文件信息集合
+     *
+     */
+    public static void createZip(HttpServletResponse response, List<Map<String,String>> fileList ) {
+
+        try {
+            //设置下载的文件名称, 注意中文名需要做编码类型转换
+            response.setContentType("application/x-octet-stream");
+            response.setHeader("Content-Disposition", "attachment;");
+            response.setCharacterEncoding("utf-8");
+            //创建zip输出流
+            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
+            byte[] buffer = new byte[1024];
+            BufferedInputStream bufferStream = null;
+            int index = 1;
+            for (int i = 0 ; i < fileList.size() ; i++) {
+                //设置zip里面每个文件的名称
+                zos.putNextEntry(new ZipEntry(fileList.get(i).get("fileName").toString()));
+                //根据文件地址获取输入流
+                InputStream is = new URL(fileList.get(i).get("url").toString()).openConnection().getInputStream();
+                int length;
+                while ((length = is.read(buffer)) > 0) {
+                    zos.write(buffer, 0, length);
+                }
+                is.close();
+                index ++;
+            }
+            zos.closeEntry();
+            zos.close();
+            zos.flush();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+
+    }
+}