Bläddra i källkod

试玩模块创建和优化3

zhaoxian 4 år sedan
förälder
incheckning
8ac2fe11f2

+ 43 - 76
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/FileUtil.java

@@ -16,7 +16,6 @@ import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.URL;
 import java.util.Date;
-import java.util.List;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipOutputStream;
 
@@ -102,77 +101,25 @@ public class FileUtil {
                 os.write(buffer, 0, bytesRead);
                 os.flush();
             }
-            os.close();
-            is.close();
+
         } catch (Exception e) {
             log.error(" ========== 文件下载到本地异常:", e);
             return null;
-        }
-        return realPath;
-    }
-
-    /**
-     * 文件压缩方法
-     *
-     * @param list
-     * @param zipfilename
-     * @param basePath
-     * @param vid
-     * @throws
-     * @Title: listToZip
-     * @date 2020年1月20日
-     */
-    public static String listToZip(List<String> list, String localPath, String zipfilename) {
-        long start = System.currentTimeMillis();
-        FileInputStream is = null;
-        ZipOutputStream zos = null;
-        String realPath = localPath + "/newFiles/" + zipfilename;
-        try {
-            if (list != null && list.size() > 0) {
-                File f = new File(localPath, "newFiles");
-                if (!f.exists()) {
-                    boolean mkdirFlag = f.mkdirs();
-                    if (!mkdirFlag) {
-                        log.error(" ==========压缩, 创建临时文件夹失败 ========== ");
-                        return null;
-                    }
+        } finally {
+            try {
+                if (os != null) {
+                    os.close();
                 }
-                // 创建zip文件输出流
-                zos = new ZipOutputStream(new FileOutputStream(new File(realPath)));
-                File file = null;
-                String path = "";
-                for (int i = 0; i < list.size(); i++) {
-                    path = list.get(i);
-                    // file 拿到待压缩文件
-                    file = new File(path);
-                    if (file.exists()) {
-                        // 创建源文件输入流
-                        is = new FileInputStream(file);
-                        zos.putNextEntry(new ZipEntry(file.getName()));
-                        byte[] buf = new byte[2048];
-                        int length = -1;
-                        while ((length = is.read(buf)) != -1) {
-                            zos.write(buf, 0, length);
-                            zos.flush();
-                        }
-                        zos.closeEntry();
-                        is.close();
-                    } else {
-                        log.warn("[ ======= {} 源文件不存在 ======= ]", path);
-                        return null;
-                    }
+                if (is != null) {
+                    is.close();
                 }
+            } catch (IOException e) {
+                e.printStackTrace();
             }
-        } catch (Exception e) {
-            log.error("[ ==========压缩文件异常 ========== ]", e);
-            return null;
         }
-        long end = System.currentTimeMillis();
-        log.info("文件压缩完成,耗时:{} ms", (end - start));
         return realPath;
     }
 
-
     /**
      * 通过MultipartFile获取本地下载路径
      *
@@ -182,11 +129,18 @@ public class FileUtil {
      * @author ZHAOXA
      */
     public static String approvalFile(MultipartFile filecontent, String path) {
-        InputStream is = null;
         OutputStream os = null;
+        InputStream inputStream = null;
         String fileName = filecontent.getOriginalFilename();
         try {
-            is = filecontent.getInputStream();
+            inputStream = filecontent.getInputStream();
+        } catch (IOException e) {
+            log.error("获取文件流异常");
+        }
+        try {
+            byte[] bs = new byte[1024];
+            // 读取到的数据长度
+            int len;
             // 输出的文件流保存到本地文件
             File tempFile = new File(path);
             if (!tempFile.exists()) {
@@ -194,15 +148,19 @@ public class FileUtil {
             }
             os = new FileOutputStream(tempFile.getPath() + "/" + File.separator + fileName);
             // 开始读取
-            int len;
-            byte[] bs = new byte[1024];
-            while ((len = is.read(bs)) != -1) {
+            while ((len = inputStream.read(bs)) != -1) {
                 os.write(bs, 0, len);
             }
-            os.close();
-            is.close();
         } catch (Exception e) {
             log.error("获取文件的本地路径失败", e);
+        } finally {
+            // 完毕,关闭所有链接
+            try {
+                os.close();
+                inputStream.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
         }
         return path + fileName;
     }
@@ -215,24 +173,32 @@ public class FileUtil {
      * @Description
      * @author xukaixun
      */
-    public static String zipCompress(String zipPath, File sourceFile) {
+    public static String zipCompress(String zipSavePath, File sourceFile) {
         try {
             //创建zip输出流
-            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath));
+            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipSavePath));
             File[] fileList = sourceFile.listFiles();
-            if (fileList.length != 0) {
+            if (fileList.length != 0)//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
+            {
                 for (File file : fileList) {
-                    //根据filename判断是否要最外层文件夹
-                    compress(zos, file, file.getName());
+                    compress(zos, file, sourceFile.getName() + "/" + file.getName());
                 }
                 zos.close();
             }
         } catch (Exception e) {
-            log.error("压缩文件异常: {}, zipSavePath={}, sourceFile={}", e, zipPath, sourceFile.getName());
+            log.error("zip compress file exception: {}, zipSavePath={}, sourceFile={}", e, zipSavePath, sourceFile.getName());
         }
-        return zipPath;
+        return zipSavePath;
     }
 
+    /**
+     * 递归压缩文件
+     *
+     * @param
+     * @return void
+     * @throws
+     * @author ZHAOXA
+     */
     private static void compress(ZipOutputStream zos, File sourceFile, String fileName) throws Exception {
         if (sourceFile.isDirectory()) {
             //如果是文件夹,取出文件夹中的文件(或子文件夹)
@@ -266,4 +232,5 @@ public class FileUtil {
         }
     }
 
+
 }

+ 3 - 0
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/mapper/xml/ShiwanFileUploadMapper.xml

@@ -23,6 +23,9 @@
         <if test="parentId != null and parentId != '' ">
             and parent_id = #{parentId}
         </if>
+        <if test="signature != null and signature != '' ">
+            and signature = #{signature}
+        </if>
     </select>
     <select id="selectListByParentId" resultType="cn.com.ctop.shiwan.modules.entity.ShiwanFileUpload">
         SELECT

+ 21 - 10
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/service/ShiwanFileUploadServiceImpl.java

@@ -51,7 +51,6 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
 
     @Override
     public ShiwanFileUpload saveOrUpdateFile(MultipartFile file, String userId, Long accountId, String fileType, Long parentId, String uuid) {
-        ShiwanFileUpload existFiles = getExistFiles(userId, accountId, file.getOriginalFilename(), fileType, parentId);
         StringBuffer path = new StringBuffer();
         path.append(downloadPath).append(DateUtils.getNowDate(DateUtils.WEB_FORMAT)).append("/").append(UUID.randomUUID().toString()).append("/");
         log.info("-------下载到服务器地址:{}", path.toString());
@@ -63,6 +62,7 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
         } catch (IOException e) {
             log.error("获取MD5签名失败", e);
         }
+        ShiwanFileUpload existFiles = getExistFiles(userId, accountId, file.getOriginalFilename(), fileType, parentId, md5);
         if (!Check.isNull(existFiles)) {
             long start = System.currentTimeMillis();
             existFiles.setSignature(md5);
@@ -84,9 +84,9 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
             fileUpload.setUserId(userId);
             fileUpload.setAccountId(accountId);
             fileUpload.setFileType(fileType);
-            fileUpload.setParentId(parentId);
             try {
-                shiwanFileUpload = saveFile(file, fileUpload, uuid);
+                //新增zip包
+                shiwanFileUpload = saveFile(file, fileUpload, null);
             } catch (IOException e) {
                 log.error("新增文件,上传SOC异常", e);
             }
@@ -121,11 +121,12 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
         try {
             inputStream = file.getInputStream();
             resultFile = CosUtils.uploadDetailInputStreamV2(inputStream, existFiles.getCfileName(), existFiles.getFileSuffix(), file.getSize(), url);
-            inputStream.close();
         } catch (IOException e) {
             log.error("更新文件,上传COS失败", e);
         } finally {
-            inputStream.close();
+            if (inputStream != null) {
+                inputStream.close();
+            }
         }
         QueryWrapper<ShiwanFileUpload> queryWrapper = new QueryWrapper<>();
         queryWrapper.eq("id", existFiles.getId());
@@ -158,12 +159,13 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
         InputStream inputStream = null;
         try {
             inputStream = file.getInputStream();
-            resultFile = CosUtils.uploadDetailInputStream(inputStream, filename, fileSuffix, file.getSize(), url);
-            inputStream.close();
+            resultFile = CosUtils.uploadDetailInputStreamV2(inputStream, filename, fileSuffix, file.getSize(), url);
         } catch (IOException e) {
             log.error("上传COS异常", e);
         } finally {
-            inputStream.close();
+            if (inputStream != null) {
+                inputStream.close();
+            }
         }
         if (!Check.isNull(resultFile)) {
             fileUpload.setCfileName(resultFile.getCFileName());
@@ -325,6 +327,14 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
             shiwanFileUpload.setAccountId(newZipEntity.getAccountId());
             shiwanFileUpload.setFileType(newZipEntity.getFileType());
             shiwanFileUpload.setParentId(newZipEntity.getId());
+            String urlpath = url.substring(0, url.lastIndexOf("/"));
+            String lastFileName = urlpath.substring(urlpath.lastIndexOf("/") + 1);
+            String cosFilePath = "";
+            if ("innerFiles".equals(lastFileName)) {
+                cosFilePath = newZipEntity.getCfileName();
+            } else {
+                cosFilePath = newZipEntity.getCfileName().concat("/").concat(lastFileName);
+            }
             try {
                 shiwanFileUpload.setSignature(LoadFileUtil.getMD5(url));
             } catch (IOException e) {
@@ -332,7 +342,7 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
             }
             mulFileByPath = FileUtil.getMulFileByPath(url);
             try {
-                saveFile(mulFileByPath, shiwanFileUpload, newZipEntity.getCfileName());
+                saveFile(mulFileByPath, shiwanFileUpload, cosFilePath);
             } catch (IOException e) {
                 log.error("新增内部文件,上传SOC异常", e);
             }
@@ -363,13 +373,14 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
      * @throws
      * @author ZHAOXA
      */
-    private ShiwanFileUpload getExistFiles(String userId, Long accountId, String fileName, String fileType, Long parentId) {
+    private ShiwanFileUpload getExistFiles(String userId, Long accountId, String fileName, String fileType, Long parentId, String md5) {
         JSONObject job = new JSONObject();
         job.put("useId", userId);
         job.put("accountId", accountId);
         job.put("fileName", fileName);
         job.put("fileType", fileType);
         job.put("parentId", parentId);
+        job.put("signature", md5);
         ShiwanFileUpload fileEntity = shiwanFileUploadMapper.selectEntity(job);
         if (Check.isNull(fileEntity)) {
             return null;