zhijiezhao 2 роки тому
батько
коміт
df12706e18

+ 15 - 1
src/main/java/com/caimei/controller/admin/auth/DatabaseApi.java

@@ -1,5 +1,6 @@
 package com.caimei.controller.admin.auth;
 
+import com.caimei.model.ResponseJson;
 import com.caimei.model.vo.FileTreeVo;
 import com.caimei.service.data.DatabaseService;
 import io.swagger.annotations.Api;
@@ -30,9 +31,22 @@ public class DatabaseApi {
     @ApiOperation("获取当前路径下文件")
     @ApiImplicitParam(name = "fileId",value = "文件Id")
     @GetMapping("/path/file")
-    public FileTreeVo getFileById(Integer fileId) {
+    public ResponseJson<FileTreeVo> getFileById(Integer fileId) {
        return databaseService.getFileById(fileId);
     }
 
 
+    @ApiOperation("创建文件夹")
+    @ApiImplicitParam(name = "fileId",value = "当前文件夹Id")
+    @GetMapping("/path/package")
+    public ResponseJson createPackage(Integer fileId,String packageName){
+        return databaseService.createPackage(fileId,packageName);
+    }
+
+    @ApiOperation("下载文件夹")
+    @ApiImplicitParam(name = "fileId",value = "当前文件夹Id")
+    @GetMapping("/path/package/zip")
+    public void downLoadPackageZip(Integer fileId,String packageName, HttpServletResponse response){
+        databaseService.downLoadZip(fileId,packageName,response);
+    }
 }

+ 6 - 0
src/main/java/com/caimei/mapper/cmMapper/FileMapper.java

@@ -52,4 +52,10 @@ public interface FileMapper {
     FileTreeVo findFileById(Integer fileId);
 
     List<FileTreeVo> findFileChild(Integer fileId);
+
+    void creatPackage(@Param("fileId")Integer fileId,@Param("packageName") String packageName);
+
+    List<FileTreeVo> findSonFiles(Integer fileId);
+
+    List<FileTreeVo> findSonPackage(@Param("fileId")Integer fileId,@Param("selectFor")Integer selectFor);
 }

+ 5 - 0
src/main/java/com/caimei/model/vo/FileTreeVo.java

@@ -3,6 +3,7 @@ package com.caimei.model.vo;
 import lombok.Data;
 
 import java.io.Serializable;
+import java.util.Date;
 import java.util.List;
 
 /**
@@ -42,4 +43,8 @@ public class FileTreeVo implements Serializable {
      * 子级文件
      */
     protected List<FileTreeVo> childList;
+    /**
+     * 文件保存时间
+     */
+    private Date saveTime;
 }

+ 8 - 1
src/main/java/com/caimei/service/data/DatabaseService.java

@@ -1,10 +1,17 @@
 package com.caimei.service.data;
 
+import com.caimei.model.ResponseJson;
 import com.caimei.model.vo.FileTreeVo;
 
+import javax.servlet.http.HttpServletResponse;
+
 /**
  * @author zzj
  */
 public interface DatabaseService {
-    FileTreeVo getFileById(Integer fileId);
+    ResponseJson<FileTreeVo> getFileById(Integer fileId);
+
+    ResponseJson createPackage(Integer fileId,String packageName);
+
+    void downLoadZip(Integer fileId,String packageName,HttpServletResponse response);
 }

+ 106 - 3
src/main/java/com/caimei/service/data/impl/DatabaseServiceImpl.java

@@ -1,12 +1,24 @@
 package com.caimei.service.data.impl;
 
 import com.caimei.mapper.cmMapper.FileMapper;
+import com.caimei.model.ResponseJson;
 import com.caimei.model.vo.FileTreeVo;
 import com.caimei.service.data.DatabaseService;
+import com.caimei.utils.FileZipUtils;
+import com.caimei.utils.OSSUtils;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
+import org.springframework.util.Assert;
 
 import javax.annotation.Resource;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
  * @author zzj
@@ -18,10 +30,101 @@ public class DatabaseServiceImpl implements DatabaseService {
     @Resource
     private FileMapper fileMapper;
 
+    @Value("${spring.profiles.active}")
+    private String active;
+
     @Override
-    public FileTreeVo getFileById(Integer fileId) {
-        FileTreeVo fileTree=fileMapper.findFileById(fileId);
+    public ResponseJson<FileTreeVo> getFileById(Integer fileId) {
+        FileTreeVo fileTree = fileMapper.findFileById(fileId);
         fileTree.setChildList(fileMapper.findFileChild(fileId));
-        return fileTree;
+        return ResponseJson.success(fileTree);
+    }
+
+    @Override
+    public ResponseJson createPackage(Integer fileId, String packageName) {
+        fileMapper.creatPackage(fileId, packageName);
+        return ResponseJson.success();
+    }
+
+    @Override
+    public void downLoadZip(Integer fileId, String packageName, HttpServletResponse response) {
+        //1.查下一级所有文件
+        List<FileTreeVo> sonFiles = fileMapper.findSonFiles(fileId);
+        //2.有package则在服务器固定路径new file.mkdir
+        StringBuilder filePath = new StringBuilder("/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/");
+        filePath = filePath.append(packageName + "/");
+        if ("dev".equals(active)) {
+            filePath = new StringBuilder("D:\\caimei-workSpace\\file\\");
+            filePath.append(packageName);
+        }
+        String zipPath = filePath.toString();
+        File fil = new File(filePath.toString());
+        fil.mkdirs();
+        recursion(fileId, filePath);
+        //压缩
+        FileZipUtils.compress(zipPath, "", true);
+        String s = zipPath + ".zip";
+        String fileName=packageName+".zip";
+        File file = new File(s);
+        try {
+            if(file.exists()){
+                FileInputStream fileInputStream = new FileInputStream(file);
+                ServletOutputStream outputStream = response.getOutputStream();
+                // 设置下载文件的mineType,告诉浏览器下载文件类型
+    //            int i = fileName.lastIndexOf(".");
+    //            String substring = fileName.substring(i + 1, filePath.length());
+    //            response.setContentType(substring);
+                // 设置一个响应头,无论是否被浏览器解析,都下载
+                response.setHeader("Content-disposition", "attachment; filename=" + fileName);
+                byte[] bytes = new byte[1024];
+                int len;
+                while ((len = fileInputStream.read(bytes)) != -1) {
+                    outputStream.write(bytes, 0, len);
+                }
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+    //todo 一级包会重复,recursion中filepath会重复
+    private void recursion(Integer fileId, StringBuilder filePath) {
+        //1.如果当前目录存在普通文件,下载当前目录下的文件到文件夹中
+        List<FileTreeVo> commonFile = existsPackageOrCommonFile(fileId, 2);
+        if (null != commonFile && commonFile.size() > 0) {
+            commonFile.forEach(c -> {
+                String fileName = "";
+                if ("dev".equals(active)) {
+                    fileName = filePath + "\\" + c.getFileName();
+                } else {
+                    fileName = filePath + "/" + c.getFileName();
+                }
+                OSSUtils.downFileByFilePath("authFile/", c.getOssName(), fileName);
+            });
+        }
+        //2.如果存在文件夹循环文件夹,递归本方法
+        List<FileTreeVo> packages = existsPackageOrCommonFile(fileId, 1);
+        if (null != packages && packages.size() > 0) {
+            for (FileTreeVo aPackage : packages) {
+                if ("dev".equals(active)) {
+                    filePath.append("\\" + aPackage.getFileName());
+                } else {
+                    filePath.append(aPackage.getFileName() + "/");
+                }
+                File fil = new File(filePath.toString());
+                fil.mkdirs();
+                recursion(aPackage.getId(), filePath);
+            }
+        }
+    }
+
+    /**
+     * selectFor 1文件夹package,2普通文件
+     *
+     * @param fileId
+     * @param selectFor
+     * @return
+     */
+    private List<FileTreeVo> existsPackageOrCommonFile(Integer fileId, Integer selectFor) {
+        return fileMapper.findSonPackage(fileId, selectFor);
     }
 }

+ 136 - 0
src/main/java/com/caimei/utils/FileZipUtils.java

@@ -0,0 +1,136 @@
+package com.caimei.utils;
+
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.*;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+@Slf4j
+public class FileZipUtils {
+
+    /**
+     * 压缩文件
+     * @param f 原文件
+     * @param baseDir 打包根目录
+     * @param zos 压缩文件
+     * @param deleteSourceFile 是否需要删除原文件,例如:true=删除原文件、false=不删除原文件
+     */
+    public static void compress(File f, String baseDir, ZipOutputStream zos, boolean deleteSourceFile) {
+        if(!f.exists()){
+            log.info("待压缩的文件目录或文件"+f.getName()+"不存在");
+            return;
+        }
+        File[] fs = f.listFiles();
+        BufferedInputStream bis = null;
+        //ZipOutputStream zos = null;
+        byte[] bufs = new byte[1024*10];
+        FileInputStream fis = null;
+        try{
+            //zos = new ZipOutputStream(new FileOutputStream(zipFile));
+            for(int i=0; i<fs.length; i++){
+                String fName =  fs[i].getName();
+                log.info("压缩:" + baseDir+fName);
+                if(fs[i].isFile()){
+                    ZipEntry zipEntry = new ZipEntry(baseDir+fName);//
+                    zos.putNextEntry(zipEntry);
+                    //读取待压缩的文件并写进压缩包里
+                    fis = new FileInputStream(fs[i]);
+                    bis = new BufferedInputStream(fis, 1024*10);
+                    int read = 0;
+                    while((read=bis.read(bufs, 0, 1024*10))!=-1){
+                        zos.write(bufs, 0, read);
+                    }
+                    //如果需要删除源文件,则需要执行下面2句
+                    if (deleteSourceFile) {
+                        fis.close();
+                        fs[i].delete();
+                    }
+
+                }
+                else if(fs[i].isDirectory()){
+                    compress(fs[i], baseDir+fName+"/", zos, false);
+                }
+            }//end for
+        }catch  (IOException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } finally{
+            //关闭流
+            try {
+                if (null!=bis) {
+                    bis.close();
+                }
+                //if(null!=zos)
+                //zos.close();
+                if (null!=fis) {
+                    fis.close();
+                }
+            } catch (IOException e) {
+                // TODO Auto-generated catch block
+                e.printStackTrace();
+            }
+        }
+
+    }
+
+    /**
+     * 打包指定路径的文件夹
+     * @param sourceFilePath 源文件加地址,例如:C:\\test 必填
+     * @param baseDir 打包的根目录名,例如:download/ 非必填
+     * @param deleteSourceFile 是否需要删除原文件,例如:true=删除原文件、false=不删除原文件 必填
+     */
+    public static void compress(String sourceFilePath, String baseDir, boolean deleteSourceFile) {
+        File sourceDir = new File(sourceFilePath);
+        File zipFile = new File(sourceFilePath+".zip");
+        ZipOutputStream zos = null;
+        try {
+            zos = new ZipOutputStream(new FileOutputStream(zipFile));
+            compress(sourceDir, baseDir, zos, deleteSourceFile);
+        } catch (FileNotFoundException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } finally{
+            if (zos!=null) {
+                try {
+                    zos.close();
+                } catch (IOException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                }
+            }
+        }
+    }
+
+    /**
+     * 递归查询当前目录下所有文件
+     * @return
+     */
+    public static File[] getFileName(String path) {
+        File f = new File(path);//获取路径
+        long time = f.lastModified();
+        Date date = new Date(time);
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd E HH:mm");
+        String newtime = sdf.format(date);
+        log.info("最后一次修改时间-----》"+newtime);
+        log.info("文件长度----------------->"+f.length());
+        if (!f.exists()) {
+            log.info(path + " not exists");//不存在就输出
+            return null;
+        }
+        File fa[] = f.listFiles();//用数组接收  F:笔记总结C#, F:笔记总结if语句.txt
+        for (int i = 0; i < fa.length; i++) {//循环遍历
+            File fs = fa[i];//获取数组中的第i个
+            if (fs.isDirectory()) {
+                log.info(fs.getName() + " [目录]");//如果是目录就输出
+            } else {
+                log.info(fs.getName());//否则直接输出
+            }
+        }
+        return fa;
+    }
+
+
+}

+ 10 - 0
src/main/java/com/caimei/utils/OSSUtils.java

@@ -220,4 +220,14 @@ public class OSSUtils {
         // 关闭OSSClient。
         ossClient.shutdown();
     }
+
+    public static void downFileByFilePath(String path, String ossName, String fileName) {
+        // 创建OSSClient实例。
+        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
+        String filePath = active + "/" + path + ossName;
+        ossClient.getObject(new GetObjectRequest(privateBucket, filePath), new File(fileName));
+        // 关闭OSSClient。
+        ossClient.shutdown();
+    }
 }

+ 18 - 0
src/main/resources/mapper/FileMapper.xml

@@ -11,6 +11,10 @@
         insert into cm_brand_course_file (title, name, ossName, type, module, createTime)
         values (#{title}, #{name}, #{ossName}, #{fileType}, #{fileModule}, NOW());
     </insert>
+    <insert id="creatPackage">
+        insert into cm_tree_file(parentId, fileType, fileName,saveTime)
+        values (#{fileId},'package',#{packageName},now())
+    </insert>
     <update id="updateFileByFileId">
         update cm_brand_file
         set title       = #{title},
@@ -146,4 +150,18 @@
         select id,parentId,fileType,fileName,ossUrl,saveTime
         from cm_tree_file where parentId = #{fileId}
     </select>
+    <select id="findSonFiles" resultType="com.caimei.model.vo.FileTreeVo">
+        select id,parentId,fileType,fileName,ossUrl,saveTime from cm_tree_file
+        where parentId=#{fileId}
+    </select>
+    <select id="findSonPackage" resultType="com.caimei.model.vo.FileTreeVo">
+        select id,parentId,fileType,fileName,ossName from cm_tree_file
+        where parentId =#{fileId}
+        <if test="selectFor == 1">
+            and fileType = 'package'
+        </if>
+        <if test="selectFor == 2">
+            and fileType != 'package'
+        </if>
+    </select>
 </mapper>