浏览代码

fix:oss fss下载到本地目录,文件名相同的文件在后面加(序号)

caozixuan 3 年之前
父节点
当前提交
4dfdf32e70
共有 1 个文件被更改,包括 33 次插入4 次删除
  1. 33 4
      teachcloud-common/src/main/java/com/qmth/teachcloud/common/util/FileStoreUtil.java

+ 33 - 4
teachcloud-common/src/main/java/com/qmth/teachcloud/common/util/FileStoreUtil.java

@@ -156,14 +156,19 @@ public class FileStoreUtil {
      * @throws IOException 异常
      */
     public File saveLocal(InputStream inputStream, String dirPath) throws IOException {
-        File desFile = new File(dirPath);
+        String fileName = dirPath.substring(dirPath.lastIndexOf(File.separator) + 1);
+        String parentPath = dirPath.substring(0,dirPath.lastIndexOf(File.separator)) + File.separator;
+        String name = fileName.substring(0,fileName.lastIndexOf('.'));
+        String suffix = fileName.substring(fileName.lastIndexOf('.'));
+
+        File desFile = buildSingleFileName(parentPath,name,suffix,0);
         if (!desFile.exists()) {
             desFile.getParentFile().mkdirs(); //目标文件目录不存在的话需要创建目录
             desFile.createNewFile();
         }
-        if (desFile.length() > 0) {
-            return desFile;
-        }
+//        if (desFile.length() > 0) {
+//            return desFile;
+//        }
         try {
             FileUtils.copyInputStreamToFile(inputStream, desFile);
             return desFile;
@@ -173,4 +178,28 @@ public class FileStoreUtil {
             }
         }
     }
+
+    /**
+     * 构建唯一的文件名称
+     * @param path 文件路径
+     * @param fileName 文件名称
+     * @param suffix 文件后缀
+     * @param index 当前下标,初次为0
+     * @return 唯一的文件名称
+     */
+    public static File buildSingleFileName(String path, String fileName, String suffix, Integer index){
+        File file;
+        //下标不等于0开始拼后缀
+        if (index != 0) {
+            file = new File(path + fileName + "(" + index + ")" + suffix);
+        } else {
+            file = new File(path + fileName + suffix);
+        }
+        //判断文件是否存在 文件不存在退出递归
+        if (file.isFile()) {
+            //每次递归给下标加1
+            file = buildSingleFileName(path, fileName, suffix, ++index);
+        }
+        return file;
+    }
 }