zhijiezhao 2 年 前
コミット
8636804f31

+ 6 - 0
pom.xml

@@ -41,6 +41,12 @@
             <groupId>org.springframework.boot</groupId>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
             <artifactId>spring-boot-starter-web</artifactId>
         </dependency>
         </dependency>
+        <!-- oss获取token -->
+        <dependency>
+            <groupId>com.aliyun</groupId>
+            <artifactId>aliyun-java-sdk-sts</artifactId>
+            <version>3.0.0</version>
+        </dependency>
         <!--<dependency>
         <!--<dependency>
             <groupId>org.springframework.boot</groupId>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-security</artifactId>
             <artifactId>spring-boot-starter-security</artifactId>

+ 13 - 0
src/main/java/com/caimei/controller/admin/auth/DatabaseApi.java

@@ -15,6 +15,7 @@ import org.springframework.web.bind.annotation.RestController;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
 import java.io.IOException;
+import java.util.HashMap;
 
 
 /**
 /**
  * @author zzj
  * @author zzj
@@ -49,4 +50,16 @@ public class DatabaseApi {
     public void downLoadPackageZip(Integer fileId,String packageName, HttpServletResponse response){
     public void downLoadPackageZip(Integer fileId,String packageName, HttpServletResponse response){
         databaseService.downLoadZip(fileId,packageName,response);
         databaseService.downLoadZip(fileId,packageName,response);
     }
     }
+
+    @ApiOperation("上传结果")
+    @GetMapping("/oss/upload/result")
+    public ResponseJson getOssUploadResult(String fileName,String ossName,String ossUrl,String fileSize,Integer parentId){
+        return databaseService.getOssUploadResult(fileName,ossName,ossUrl,fileSize,parentId);
+    }
+
+    @ApiOperation("获取阿里云token")
+    @GetMapping("/oss/token")
+    public ResponseJson<HashMap<String,String>> ossTokenGet(){
+        return databaseService.ossTokenGet();
+    }
 }
 }

+ 5 - 3
src/main/java/com/caimei/controller/admin/auth/UploadApi.java

@@ -1,6 +1,7 @@
 package com.caimei.controller.admin.auth;
 package com.caimei.controller.admin.auth;
 
 
 import com.caimei.service.auth.UploadService;
 import com.caimei.service.auth.UploadService;
+import com.caimei.service.data.DatabaseService;
 import com.caimei.utils.OSSUtils;
 import com.caimei.utils.OSSUtils;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiImplicitParam;
 import io.swagger.annotations.ApiImplicitParam;
@@ -36,6 +37,7 @@ public class UploadApi {
     @Value("${caimei.imageDomain}")
     @Value("${caimei.imageDomain}")
     private String imageDomain;
     private String imageDomain;
     private final UploadService uploadService;
     private final UploadService uploadService;
+    private final DatabaseService databaseService;
 
 
     /**
     /**
      * 上传图片
      * 上传图片
@@ -46,7 +48,7 @@ public class UploadApi {
     public Map<String, Object> uploadImage(MultipartFile file) throws IOException {
     public Map<String, Object> uploadImage(MultipartFile file) throws IOException {
         Map<String, Object> map = new HashMap<>(2);
         Map<String, Object> map = new HashMap<>(2);
         String saveFile;
         String saveFile;
-        if (file != null ) {
+        if (file != null) {
             // 保存文件
             // 保存文件
             saveFile = uploadService.saveFile(file);
             saveFile = uploadService.saveFile(file);
             map.put("data", saveFile);
             map.put("data", saveFile);
@@ -60,11 +62,10 @@ public class UploadApi {
     }
     }
 
 
 
 
-
     @ApiOperation("上传文件")
     @ApiOperation("上传文件")
     @ApiImplicitParam(name = "file", value = "文件", required = true)
     @ApiImplicitParam(name = "file", value = "文件", required = true)
     @PostMapping("/file")
     @PostMapping("/file")
-    public Map<String, Object> uploadFile(MultipartFile file) throws IOException {
+    public Map<String, Object> uploadFile(MultipartFile file,Integer parentId) throws IOException {
         Map<String, Object> map = new HashMap<>(2);
         Map<String, Object> map = new HashMap<>(2);
         String fileAllName = file.getOriginalFilename();
         String fileAllName = file.getOriginalFilename();
         String realName = fileAllName.substring(0, fileAllName.lastIndexOf("."));
         String realName = fileAllName.substring(0, fileAllName.lastIndexOf("."));
@@ -86,6 +87,7 @@ public class UploadApi {
             map.put("previewUrl", previewUrl);
             map.put("previewUrl", previewUrl);
             map.put("downloadUrl", filePath);
             map.put("downloadUrl", filePath);
             map.put("fileName", fileName);
             map.put("fileName", fileName);
+            databaseService.insertNewFile(fileName, filePath, previewUrl,parentId,fileType);
             map.put("msg", "上传成功");
             map.put("msg", "上传成功");
             logger.info(">>>>>>>>>>>>>>>>文件上传成功:" + previewUrl);
             logger.info(">>>>>>>>>>>>>>>>文件上传成功:" + previewUrl);
         } else {
         } else {

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

@@ -58,4 +58,6 @@ public interface FileMapper {
     List<FileTreeVo> findSonFiles(Integer fileId);
     List<FileTreeVo> findSonFiles(Integer fileId);
 
 
     List<FileTreeVo> findSonPackage(@Param("fileId")Integer fileId,@Param("selectFor")Integer selectFor);
     List<FileTreeVo> findSonPackage(@Param("fileId")Integer fileId,@Param("selectFor")Integer selectFor);
+
+    void insertNewFile(FileTreeVo fileTreeVo);
 }
 }

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

@@ -47,4 +47,8 @@ public class FileTreeVo implements Serializable {
      * 文件保存时间
      * 文件保存时间
      */
      */
     private Date saveTime;
     private Date saveTime;
+    /**
+     * 文件大小
+     */
+    private String fileSize;
 }
 }

+ 9 - 2
src/main/java/com/caimei/service/data/DatabaseService.java

@@ -4,6 +4,7 @@ import com.caimei.model.ResponseJson;
 import com.caimei.model.vo.FileTreeVo;
 import com.caimei.model.vo.FileTreeVo;
 
 
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpServletResponse;
+import java.util.HashMap;
 
 
 /**
 /**
  * @author zzj
  * @author zzj
@@ -11,7 +12,13 @@ import javax.servlet.http.HttpServletResponse;
 public interface DatabaseService {
 public interface DatabaseService {
     ResponseJson<FileTreeVo> getFileById(Integer fileId);
     ResponseJson<FileTreeVo> getFileById(Integer fileId);
 
 
-    ResponseJson createPackage(Integer fileId,String packageName);
+    ResponseJson createPackage(Integer fileId, String packageName);
 
 
-    void downLoadZip(Integer fileId,String packageName,HttpServletResponse response);
+    void downLoadZip(Integer fileId, String packageName, HttpServletResponse response);
+
+    void insertNewFile(String fileName, String filePath, String previewUrl, Integer parentId,String fileType);
+
+    ResponseJson<HashMap<String, String>> ossTokenGet();
+
+    ResponseJson getOssUploadResult(String fileName, String ossName, String ossUrl, String fileSize,Integer parentId);
 }
 }

+ 65 - 22
src/main/java/com/caimei/service/data/impl/DatabaseServiceImpl.java

@@ -1,5 +1,8 @@
 package com.caimei.service.data.impl;
 package com.caimei.service.data.impl;
 
 
+import com.aliyuncs.DefaultAcsClient;
+import com.aliyuncs.IAcsClient;
+import com.aliyuncs.profile.DefaultProfile;
 import com.caimei.mapper.cmMapper.FileMapper;
 import com.caimei.mapper.cmMapper.FileMapper;
 import com.caimei.model.ResponseJson;
 import com.caimei.model.ResponseJson;
 import com.caimei.model.vo.FileTreeVo;
 import com.caimei.model.vo.FileTreeVo;
@@ -17,7 +20,9 @@ import javax.servlet.http.HttpServletResponse;
 import java.io.File;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.IOException;
+import java.util.HashMap;
 import java.util.List;
 import java.util.List;
+import java.util.UUID;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 
 /**
 /**
@@ -48,32 +53,35 @@ public class DatabaseServiceImpl implements DatabaseService {
 
 
     @Override
     @Override
     public void downLoadZip(Integer fileId, String packageName, HttpServletResponse response) {
     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 + "/");
+        //有package则在服务器固定路径new file.mkdir
+        UUID uuid = UUID.randomUUID();
+        String filePath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/" + uuid + "/";
+        filePath = filePath + packageName;
+        String zipPath = filePath;
+        String delPath = filePath;
         if ("dev".equals(active)) {
         if ("dev".equals(active)) {
-            filePath = new StringBuilder("D:\\caimei-workSpace\\file\\");
-            filePath.append(packageName);
+            filePath = "D:\\caimei-workSpace\\file\\" + uuid + "\\";
+            zipPath = filePath + packageName;
+            delPath = filePath;
+            filePath = filePath + packageName + "\\";
         }
         }
-        String zipPath = filePath.toString();
-        File fil = new File(filePath.toString());
-        fil.mkdirs();
+        boolean mkdirs = new File(filePath).mkdirs();
+        Assert.isTrue(mkdirs, "文件夹创建失败");
+
         recursion(fileId, filePath);
         recursion(fileId, filePath);
         //压缩
         //压缩
         FileZipUtils.compress(zipPath, "", true);
         FileZipUtils.compress(zipPath, "", true);
         String s = zipPath + ".zip";
         String s = zipPath + ".zip";
-        String fileName=packageName+".zip";
+        String fileName = packageName + ".zip";
         File file = new File(s);
         File file = new File(s);
         try {
         try {
-            if(file.exists()){
+            if (file.exists()) {
                 FileInputStream fileInputStream = new FileInputStream(file);
                 FileInputStream fileInputStream = new FileInputStream(file);
                 ServletOutputStream outputStream = response.getOutputStream();
                 ServletOutputStream outputStream = response.getOutputStream();
                 // 设置下载文件的mineType,告诉浏览器下载文件类型
                 // 设置下载文件的mineType,告诉浏览器下载文件类型
-    //            int i = fileName.lastIndexOf(".");
-    //            String substring = fileName.substring(i + 1, filePath.length());
-    //            response.setContentType(substring);
+                //            int i = fileName.lastIndexOf(".");
+                //            String substring = fileName.substring(i + 1, filePath.length());
+                //            response.setContentType(substring);
                 // 设置一个响应头,无论是否被浏览器解析,都下载
                 // 设置一个响应头,无论是否被浏览器解析,都下载
                 response.setHeader("Content-disposition", "attachment; filename=" + fileName);
                 response.setHeader("Content-disposition", "attachment; filename=" + fileName);
                 byte[] bytes = new byte[1024];
                 byte[] bytes = new byte[1024];
@@ -81,40 +89,75 @@ public class DatabaseServiceImpl implements DatabaseService {
                 while ((len = fileInputStream.read(bytes)) != -1) {
                 while ((len = fileInputStream.read(bytes)) != -1) {
                     outputStream.write(bytes, 0, len);
                     outputStream.write(bytes, 0, len);
                 }
                 }
+                fileInputStream.close();
+                outputStream.close();
             }
             }
         } catch (IOException e) {
         } catch (IOException e) {
             e.printStackTrace();
             e.printStackTrace();
         }
         }
+        FileZipUtils.deleteFile(new File(delPath));
+    }
+
+    @Override
+    public void insertNewFile(String fileName, String filePath, String previewUrl,Integer parentId,String fileType) {
+        FileTreeVo fileTreeVo = new FileTreeVo();
+        fileTreeVo.setFileName(fileName);
+        fileTreeVo.setOssName(filePath);
+        fileTreeVo.setOssUrl(previewUrl);
+        fileTreeVo.setParentId(parentId);
+        fileTreeVo.setFileType(fileType);
+        fileMapper.insertNewFile(fileTreeVo);
+    }
+
+    @Override
+    public ResponseJson<HashMap<String, String>> ossTokenGet() {
+        return ResponseJson.success(OSSUtils.getToken());
+    }
+
+    @Override
+    public ResponseJson getOssUploadResult(String fileName, String ossName, String ossUrl, String fileSize,Integer parentId) {
+        FileTreeVo fileTreeVo = new FileTreeVo();
+        fileTreeVo.setFileName(fileName);
+        fileTreeVo.setOssName(ossName);
+        fileTreeVo.setOssUrl(ossUrl);
+        fileTreeVo.setParentId(parentId);
+        fileTreeVo.setFileType(fileName.substring(fileName.indexOf(".")+1));
+        fileTreeVo.setFileSize(fileSize);
+        fileMapper.insertNewFile(fileTreeVo);
+        return ResponseJson.success();
     }
     }
-    //todo 一级包会重复,recursion中filepath会重复
-    private void recursion(Integer fileId, StringBuilder filePath) {
+
+    private void recursion(Integer fileId, String filePath) {
         //1.如果当前目录存在普通文件,下载当前目录下的文件到文件夹中
         //1.如果当前目录存在普通文件,下载当前目录下的文件到文件夹中
+        String finalFilePath = filePath;
         List<FileTreeVo> commonFile = existsPackageOrCommonFile(fileId, 2);
         List<FileTreeVo> commonFile = existsPackageOrCommonFile(fileId, 2);
         if (null != commonFile && commonFile.size() > 0) {
         if (null != commonFile && commonFile.size() > 0) {
             commonFile.forEach(c -> {
             commonFile.forEach(c -> {
                 String fileName = "";
                 String fileName = "";
                 if ("dev".equals(active)) {
                 if ("dev".equals(active)) {
-                    fileName = filePath + "\\" + c.getFileName();
+                    fileName = finalFilePath + "\\" + c.getFileName();
                 } else {
                 } else {
-                    fileName = filePath + "/" + c.getFileName();
+                    fileName = finalFilePath + "/" + c.getFileName();
                 }
                 }
                 OSSUtils.downFileByFilePath("authFile/", c.getOssName(), fileName);
                 OSSUtils.downFileByFilePath("authFile/", c.getOssName(), fileName);
             });
             });
         }
         }
         //2.如果存在文件夹循环文件夹,递归本方法
         //2.如果存在文件夹循环文件夹,递归本方法
         List<FileTreeVo> packages = existsPackageOrCommonFile(fileId, 1);
         List<FileTreeVo> packages = existsPackageOrCommonFile(fileId, 1);
+        HashMap<Integer, String> sonPackage = new HashMap<Integer, String>();
         if (null != packages && packages.size() > 0) {
         if (null != packages && packages.size() > 0) {
             for (FileTreeVo aPackage : packages) {
             for (FileTreeVo aPackage : packages) {
                 if ("dev".equals(active)) {
                 if ("dev".equals(active)) {
-                    filePath.append("\\" + aPackage.getFileName());
+                    filePath = finalFilePath + "\\" + aPackage.getFileName();
                 } else {
                 } else {
-                    filePath.append(aPackage.getFileName() + "/");
+                    filePath = finalFilePath + aPackage.getFileName() + "/";
                 }
                 }
                 File fil = new File(filePath.toString());
                 File fil = new File(filePath.toString());
                 fil.mkdirs();
                 fil.mkdirs();
-                recursion(aPackage.getId(), filePath);
+                sonPackage.put(aPackage.getId(), filePath);
             }
             }
         }
         }
+        sonPackage.forEach(this::recursion);
     }
     }
 
 
     /**
     /**

+ 67 - 30
src/main/java/com/caimei/utils/FileZipUtils.java

@@ -13,34 +13,35 @@ public class FileZipUtils {
 
 
     /**
     /**
      * 压缩文件
      * 压缩文件
-     * @param f 原文件
-     * @param baseDir 打包根目录
-     * @param zos 压缩文件
+     *
+     * @param f                原文件
+     * @param baseDir          打包根目录
+     * @param zos              压缩文件
      * @param deleteSourceFile 是否需要删除原文件,例如:true=删除原文件、false=不删除原文件
      * @param deleteSourceFile 是否需要删除原文件,例如:true=删除原文件、false=不删除原文件
      */
      */
     public static void compress(File f, String baseDir, ZipOutputStream zos, boolean deleteSourceFile) {
     public static void compress(File f, String baseDir, ZipOutputStream zos, boolean deleteSourceFile) {
-        if(!f.exists()){
-            log.info("待压缩的文件目录或文件"+f.getName()+"不存在");
+        if (!f.exists()) {
+            log.info("待压缩的文件目录或文件" + f.getName() + "不存在");
             return;
             return;
         }
         }
         File[] fs = f.listFiles();
         File[] fs = f.listFiles();
         BufferedInputStream bis = null;
         BufferedInputStream bis = null;
         //ZipOutputStream zos = null;
         //ZipOutputStream zos = null;
-        byte[] bufs = new byte[1024*10];
+        byte[] bufs = new byte[1024 * 10];
         FileInputStream fis = null;
         FileInputStream fis = null;
-        try{
+        try {
             //zos = new ZipOutputStream(new FileOutputStream(zipFile));
             //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);//
+            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);
                     zos.putNextEntry(zipEntry);
                     //读取待压缩的文件并写进压缩包里
                     //读取待压缩的文件并写进压缩包里
                     fis = new FileInputStream(fs[i]);
                     fis = new FileInputStream(fs[i]);
-                    bis = new BufferedInputStream(fis, 1024*10);
+                    bis = new BufferedInputStream(fis, 1024 * 10);
                     int read = 0;
                     int read = 0;
-                    while((read=bis.read(bufs, 0, 1024*10))!=-1){
+                    while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                         zos.write(bufs, 0, read);
                         zos.write(bufs, 0, read);
                     }
                     }
                     //如果需要删除源文件,则需要执行下面2句
                     //如果需要删除源文件,则需要执行下面2句
@@ -49,23 +50,23 @@ public class FileZipUtils {
                         fs[i].delete();
                         fs[i].delete();
                     }
                     }
 
 
-                }
-                else if(fs[i].isDirectory()){
-                    compress(fs[i], baseDir+fName+"/", zos, false);
+                } else if (fs[i].isDirectory()) {
+                    compress(fs[i], baseDir + fName + "/", zos, false);
                 }
                 }
             }//end for
             }//end for
-        }catch  (IOException e) {
+        } catch (IOException e) {
             // TODO Auto-generated catch block
             // TODO Auto-generated catch block
             e.printStackTrace();
             e.printStackTrace();
-        } finally{
+        } finally {
             //关闭流
             //关闭流
             try {
             try {
-                if (null!=bis) {
+                if (null != bis) {
                     bis.close();
                     bis.close();
                 }
                 }
-                //if(null!=zos)
-                //zos.close();
-                if (null!=fis) {
+//                if (null != zos) {
+//                    zos.close();
+//                }
+                if (null != fis) {
                     fis.close();
                     fis.close();
                 }
                 }
             } catch (IOException e) {
             } catch (IOException e) {
@@ -78,13 +79,14 @@ public class FileZipUtils {
 
 
     /**
     /**
      * 打包指定路径的文件夹
      * 打包指定路径的文件夹
-     * @param sourceFilePath 源文件加地址,例如:C:\\test 必填
-     * @param baseDir 打包的根目录名,例如:download/ 非必填
+     *
+     * @param sourceFilePath   源文件加地址,例如:C:\\test 必填
+     * @param baseDir          打包的根目录名,例如:download/ 非必填
      * @param deleteSourceFile 是否需要删除原文件,例如:true=删除原文件、false=不删除原文件 必填
      * @param deleteSourceFile 是否需要删除原文件,例如:true=删除原文件、false=不删除原文件 必填
      */
      */
     public static void compress(String sourceFilePath, String baseDir, boolean deleteSourceFile) {
     public static void compress(String sourceFilePath, String baseDir, boolean deleteSourceFile) {
         File sourceDir = new File(sourceFilePath);
         File sourceDir = new File(sourceFilePath);
-        File zipFile = new File(sourceFilePath+".zip");
+        File zipFile = new File(sourceFilePath + ".zip");
         ZipOutputStream zos = null;
         ZipOutputStream zos = null;
         try {
         try {
             zos = new ZipOutputStream(new FileOutputStream(zipFile));
             zos = new ZipOutputStream(new FileOutputStream(zipFile));
@@ -92,9 +94,11 @@ public class FileZipUtils {
         } catch (FileNotFoundException e) {
         } catch (FileNotFoundException e) {
             // TODO Auto-generated catch block
             // TODO Auto-generated catch block
             e.printStackTrace();
             e.printStackTrace();
-        } finally{
-            if (zos!=null) {
+        } finally {
+            if (zos != null) {
                 try {
                 try {
+                    zos.flush();
+                    zos.closeEntry();
                     zos.close();
                     zos.close();
                 } catch (IOException e) {
                 } catch (IOException e) {
                     // TODO Auto-generated catch block
                     // TODO Auto-generated catch block
@@ -106,6 +110,7 @@ public class FileZipUtils {
 
 
     /**
     /**
      * 递归查询当前目录下所有文件
      * 递归查询当前目录下所有文件
+     *
      * @return
      * @return
      */
      */
     public static File[] getFileName(String path) {
     public static File[] getFileName(String path) {
@@ -114,8 +119,8 @@ public class FileZipUtils {
         Date date = new Date(time);
         Date date = new Date(time);
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd E HH:mm");
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd E HH:mm");
         String newtime = sdf.format(date);
         String newtime = sdf.format(date);
-        log.info("最后一次修改时间-----》"+newtime);
-        log.info("文件长度----------------->"+f.length());
+        log.info("最后一次修改时间-----》" + newtime);
+        log.info("文件长度----------------->" + f.length());
         if (!f.exists()) {
         if (!f.exists()) {
             log.info(path + " not exists");//不存在就输出
             log.info(path + " not exists");//不存在就输出
             return null;
             return null;
@@ -132,5 +137,37 @@ public class FileZipUtils {
         return fa;
         return fa;
     }
     }
 
 
+    /**
+     * 文件夹删除
+     *
+     * @param file
+     * @return
+     */
+    public static Boolean deleteFile(File file) {
+        //判断文件不为null或文件目录存在
+        if (file == null || !file.exists()) {
+            log.info("文件删除失败,请检查文件是否存在以及文件路径是否正确");
+            return false;
+        }
+        //获取目录下子文件
+        File[] files = file.listFiles();
+        //遍历该目录下的文件对象
+        for (File f : files) {
+            //判断子目录是否存在子目录,如果是文件则删除
+            if (f.isDirectory()) {
+                //递归删除目录下的文件
+                deleteFile(f);
+            } else {
+                //文件删除
+                f.delete();
+                //打印文件名
+                log.info("文件名:" + f.getName());
+            }
+        }
+        //文件夹删除
+        boolean delete = file.delete();
+        System.out.println("目录名:" + file.getName());
+        return delete;
+    }
 
 
 }
 }

+ 39 - 2
src/main/java/com/caimei/utils/OSSUtils.java

@@ -4,6 +4,12 @@ import com.aliyun.oss.HttpMethod;
 import com.aliyun.oss.OSS;
 import com.aliyun.oss.OSS;
 import com.aliyun.oss.OSSClientBuilder;
 import com.aliyun.oss.OSSClientBuilder;
 import com.aliyun.oss.model.*;
 import com.aliyun.oss.model.*;
+import com.aliyuncs.DefaultAcsClient;
+import com.aliyuncs.IAcsClient;
+import com.aliyuncs.auth.sts.AssumeRoleRequest;
+import com.aliyuncs.auth.sts.AssumeRoleResponse;
+import com.aliyuncs.exceptions.ClientException;
+import com.aliyuncs.profile.DefaultProfile;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
@@ -13,6 +19,7 @@ import java.io.File;
 import java.io.IOException;
 import java.io.IOException;
 import java.net.URL;
 import java.net.URL;
 import java.util.Date;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.UUID;
 import java.util.UUID;
 
 
 @Component
 @Component
@@ -52,6 +59,36 @@ public class OSSUtils {
         active = actives;
         active = actives;
     }
     }
 
 
+    public static HashMap<String, String> getToken() {
+        //构建一个阿里云客户端,用于发起请求。
+        //设置调用者(RAM用户或RAM角色)的AccessKey ID和AccessKey Secret。
+        DefaultProfile profile = DefaultProfile.getProfile("oss-cn-shenzhen", accessKeyId, accessKeySecret);
+        IAcsClient client = new DefaultAcsClient(profile);
+
+        //构造请求,设置参数。
+        AssumeRoleRequest request = new AssumeRoleRequest();
+        request.setRegionId(endpoint);
+        request.setRoleArn("acs:ram::1565565840178476:role/caimeitst");
+        request.setRoleSessionName("TSTtest");
+        AssumeRoleResponse response = null;
+        try {
+            response = client.getAcsResponse(request);
+        } catch (ClientException e) {
+            e.printStackTrace();
+        }
+        String requestId = response.getRequestId();
+        String securityToken = response.getCredentials().getSecurityToken();
+        String accessKeySecret = response.getCredentials().getAccessKeySecret();
+        String accessKeyId = response.getCredentials().getAccessKeyId();
+        HashMap<String, String> tokenMap = new HashMap<>(5);
+        tokenMap.put("requestId", requestId);
+        tokenMap.put("accessKeyId", accessKeyId);
+        tokenMap.put("accessKeySecret", accessKeySecret);
+        tokenMap.put("securityToken", securityToken);
+        tokenMap.put("bucket", privateBucket);
+        return tokenMap;
+    }
+
     public static String ossUpload(String fileName, File file, String contentType, String contentDisposition) {
     public static String ossUpload(String fileName, File file, String contentType, String contentDisposition) {
         String url = null;
         String url = null;
         try {
         try {
@@ -126,13 +163,13 @@ public class OSSUtils {
         if (".vsd".equalsIgnoreCase(fileExtension)) {
         if (".vsd".equalsIgnoreCase(fileExtension)) {
             return "application/vnd.visio";
             return "application/vnd.visio";
         }
         }
-        if (".ppt".equalsIgnoreCase(fileExtension)  ) {
+        if (".ppt".equalsIgnoreCase(fileExtension)) {
             return "application/vnd.ms-powerpoint";
             return "application/vnd.ms-powerpoint";
         }
         }
         if (".pptx".equalsIgnoreCase(fileExtension)) {
         if (".pptx".equalsIgnoreCase(fileExtension)) {
             return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
             return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
         }
         }
-        if (".doc".equalsIgnoreCase(fileExtension) ) {
+        if (".doc".equalsIgnoreCase(fileExtension)) {
             return "application/msword";
             return "application/msword";
         }
         }
         if (".docx".equalsIgnoreCase(fileExtension)) {
         if (".docx".equalsIgnoreCase(fileExtension)) {

+ 30 - 16
src/main/resources/mapper/FileMapper.xml

@@ -1,7 +1,8 @@
 <?xml version="1.0" encoding="UTF-8" ?>
 <?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="com.caimei.mapper.cmMapper.FileMapper">
 <mapper namespace="com.caimei.mapper.cmMapper.FileMapper">
-    <insert id="insertFile" keyColumn="id" keyProperty="id" parameterType="com.caimei.model.po.FilePo" useGeneratedKeys="true">
+    <insert id="insertFile" keyColumn="id" keyProperty="id" parameterType="com.caimei.model.po.FilePo"
+            useGeneratedKeys="true">
         insert into cm_brand_file(authUserId, fileType, title, name, previewUrl, downloadUrl, auditStatus, status,
         insert into cm_brand_file(authUserId, fileType, title, name, previewUrl, downloadUrl, auditStatus, status,
                                   createTime, auditBy, auditTime)
                                   createTime, auditBy, auditTime)
         values (#{authUserId}, #{fileType}, #{title}, #{name}, #{previewUrl}, #{downloadUrl}, #{auditStatus}, #{status},
         values (#{authUserId}, #{fileType}, #{title}, #{name}, #{previewUrl}, #{downloadUrl}, #{auditStatus}, #{status},
@@ -12,8 +13,12 @@
         values (#{title}, #{name}, #{ossName}, #{fileType}, #{fileModule}, NOW());
         values (#{title}, #{name}, #{ossName}, #{fileType}, #{fileModule}, NOW());
     </insert>
     </insert>
     <insert id="creatPackage">
     <insert id="creatPackage">
-        insert into cm_tree_file(parentId, fileType, fileName,saveTime)
-        values (#{fileId},'package',#{packageName},now())
+        insert into cm_tree_file(parentId, fileType, fileName, saveTime)
+        values (#{fileId}, 'package', #{packageName}, now())
+    </insert>
+    <insert id="insertNewFile">
+        insert into cm_tree_file(parentId, fileType, saveTime, ossUrl, fileName, ossName, fileSize)
+        values (#{parentId}, #{fileType}, now(), #{ossUrl}, #{fileName}, #{ossName}, #{fileSize})
     </insert>
     </insert>
     <update id="updateFileByFileId">
     <update id="updateFileByFileId">
         update cm_brand_file
         update cm_brand_file
@@ -70,10 +75,14 @@
         where id = #{id}
         where id = #{id}
     </update>
     </update>
     <delete id="deleteFileByFileId">
     <delete id="deleteFileByFileId">
-        delete from cm_brand_file where id = #{fileId}
+        delete
+        from cm_brand_file
+        where id = #{fileId}
     </delete>
     </delete>
     <delete id="deleteCourseFileByFileId">
     <delete id="deleteCourseFileByFileId">
-        delete from cm_brand_course_file where id = #{fileId}
+        delete
+        from cm_brand_course_file
+        where id = #{fileId}
     </delete>
     </delete>
     <select id="getFileList" resultType="com.caimei.model.vo.FileListVo">
     <select id="getFileList" resultType="com.caimei.model.vo.FileListVo">
         select a.id as fileId,a.title as fileTitle,a.name as fileName,a.previewUrl as filePreviewUrl,
         select a.id as fileId,a.title as fileTitle,a.name as fileName,a.previewUrl as filePreviewUrl,
@@ -125,34 +134,39 @@
         order by createTime desc
         order by createTime desc
     </select>
     </select>
     <select id="getAuthImageData" resultType="com.caimei.model.po.ProductImagePo">
     <select id="getAuthImageData" resultType="com.caimei.model.po.ProductImagePo">
-        SELECT certificateImage as authImage,a.authParty,p.snCode
+        SELECT certificateImage as authImage, a.authParty, p.snCode
         FROM cm_brand_auth_product p
         FROM cm_brand_auth_product p
                  left join cm_brand_auth a on p.authId = a.id
                  left join cm_brand_auth a on p.authId = a.id
-                 left join cm_brand_auth_user u on a.authUserId = u.authUserId where u.authUserId = 4;
+                 left join cm_brand_auth_user u on a.authUserId = u.authUserId
+        where u.authUserId = 4;
     </select>
     </select>
     <select id="getProductImageList" resultType="com.caimei.model.po.ProductImagePo">
     <select id="getProductImageList" resultType="com.caimei.model.po.ProductImagePo">
-        SELECT p.id as productId, certificateImage,a.authParty,p.snCode
+        SELECT p.id as productId, certificateImage, a.authParty, p.snCode
         FROM cm_brand_auth_product p
         FROM cm_brand_auth_product p
                  left join cm_brand_auth a on p.authId = a.id and a.delFlag = 0
                  left join cm_brand_auth a on p.authId = a.id and a.delFlag = 0
-                 left join cm_brand_auth_user u on a.authUserId = u.authUserId where u.authUserId = #{authUserId};
+                 left join cm_brand_auth_user u on a.authUserId = u.authUserId
+        where u.authUserId = #{authUserId};
     </select>
     </select>
     <select id="getAuthImageList" resultType="com.caimei.model.vo.AuthVo">
     <select id="getAuthImageList" resultType="com.caimei.model.vo.AuthVo">
         select a.id as authId, a.authParty
         select a.id as authId, a.authParty
         from cm_brand_auth a
         from cm_brand_auth a
-            left join cm_brand_auth_user u on a.authUserId = u.authUserId
+                 left join cm_brand_auth_user u on a.authUserId = u.authUserId
         where u.authUserId = #{authUserId};
         where u.authUserId = #{authUserId};
     </select>
     </select>
     <select id="findFileById" resultType="com.caimei.model.vo.FileTreeVo">
     <select id="findFileById" resultType="com.caimei.model.vo.FileTreeVo">
-        select id,parentId,fileType,fileName,ossUrl,saveTime
-        from cm_tree_file where id = #{fileId}
+        select id, parentId, fileType, fileName, ossUrl, saveTime
+        from cm_tree_file
+        where id = #{fileId}
     </select>
     </select>
     <select id="findFileChild" resultType="com.caimei.model.vo.FileTreeVo">
     <select id="findFileChild" resultType="com.caimei.model.vo.FileTreeVo">
-        select id,parentId,fileType,fileName,ossUrl,saveTime
-        from cm_tree_file where parentId = #{fileId}
+        select id, parentId, fileType, fileName, ossUrl, saveTime
+        from cm_tree_file
+        where parentId = #{fileId}
     </select>
     </select>
     <select id="findSonFiles" resultType="com.caimei.model.vo.FileTreeVo">
     <select id="findSonFiles" resultType="com.caimei.model.vo.FileTreeVo">
-        select id,parentId,fileType,fileName,ossUrl,saveTime from cm_tree_file
-        where parentId=#{fileId}
+        select id, parentId, fileType, fileName, ossUrl, saveTime
+        from cm_tree_file
+        where parentId = #{fileId}
     </select>
     </select>
     <select id="findSonPackage" resultType="com.caimei.model.vo.FileTreeVo">
     <select id="findSonPackage" resultType="com.caimei.model.vo.FileTreeVo">
         select id,parentId,fileType,fileName,ossName from cm_tree_file
         select id,parentId,fileType,fileName,ossName from cm_tree_file