Переглянути джерело

feat-[regionDevelop]:新增图片文件排序,删除图片文件

seeseele 7 місяців тому
батько
коміт
71ab2968c7

+ 38 - 0
src/main/java/com/ruoyi/project/VRdemo/controller/RegionDevelopController.java

@@ -6,6 +6,7 @@ import java.util.List;
 import javax.servlet.http.HttpServletResponse;
 
 import com.alibaba.excel.EasyExcel;
+import com.ruoyi.common.utils.StringUtils;
 import com.ruoyi.common.utils.excel.ExcelReadUtil;
 import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
 import com.ruoyi.project.VRdemo.domain.imData.RegionDevelopImData;
@@ -87,6 +88,24 @@ public class RegionDevelopController extends BaseController {
     @Log(title = "东南亚地区发展报告", businessType = BusinessType.INSERT)
     @PostMapping
     public AjaxResult add(@RequestBody RegionDevelop regionDevelop) {
+        //获取编号为00的文件路径
+        String pathStr = regionDevelop.getPath();
+        if(StringUtils.isNull(pathStr)){
+            return error("上传文件不能为空");
+        }
+        String[] paths = pathStr.split(","); //将批量文件名转化为数组
+        String zero = "";
+        for (String s : paths) {
+            String fileName = s.substring(s.lastIndexOf("/") + 1, s.lastIndexOf(".")); //获取文件名
+            String last = fileName.substring(fileName.length() - 2); //获取文件名后面的编号
+            if (last.equals("00")) {
+                zero = s;
+            }
+        }
+        regionDevelop.setPath(zero);
+        int count = paths.length;//获取上传文件数量
+        regionDevelop.setCount((long) count);
+
         return toAjax(regionDevelopService.insertRegionDevelop(regionDevelop));
     }
 
@@ -110,6 +129,25 @@ public class RegionDevelopController extends BaseController {
         return toAjax(regionDevelopService.deleteRegionDevelopByIds(ids));
     }
 
+    /**
+     * 删除东南亚地区发展报告(包括文件)
+     */
+    @PreAuthorize("@ss.hasAnyRoles('admin,xmg')")
+    @Log(title = "东南亚地区发展报告", businessType = BusinessType.DELETE)
+    @DeleteMapping("/deleteFile/{id}")
+    public String deleteFile(@PathVariable("id") Long id) {
+        try {
+            boolean success = regionDevelopService.deleteFile(id);
+            if (success) {
+                return "文件删除成功.";
+            } else {
+                return "文件删除失败.";
+            }
+        } catch (NumberFormatException e) {
+            return "文件格式错误";
+        }
+    }
+
 
     /**
      * 导出东南亚地区发展报告列表

+ 8 - 0
src/main/java/com/ruoyi/project/VRdemo/service/IRegionDevelopService.java

@@ -69,4 +69,12 @@ public interface IRegionDevelopService {
      */
     int deleteRegionDevelopById(Long id);
 
+    /**
+     * 删除文件
+     *
+     * @param id
+     * @return
+     */
+    boolean deleteFile(Long id);
+
 }

+ 210 - 27
src/main/java/com/ruoyi/project/VRdemo/service/impl/RegionDevelopServiceImpl.java

@@ -1,10 +1,17 @@
 package com.ruoyi.project.VRdemo.service.impl;
 
+import java.io.File;
+import java.util.ArrayList;
 import java.util.List;
 
+import com.ruoyi.common.constant.Constants;
 import com.ruoyi.common.utils.DateUtils;
 import com.ruoyi.common.utils.SecurityUtils;
+import com.ruoyi.common.utils.StringUtils;
+import com.ruoyi.framework.config.RuoYiConfig;
+import com.ruoyi.project.VRdemo.domain.NoteNationData;
 import com.ruoyi.project.VRdemo.domain.RegionDevelop;
+import com.ruoyi.project.VRdemo.domain.StudyData;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import com.ruoyi.project.VRdemo.mapper.RegionDevelopMapper;
@@ -60,6 +67,44 @@ public class RegionDevelopServiceImpl implements IRegionDevelopService {
     }
 
     /**
+     * 导入数据
+     *
+     * @param dataList      数据列表
+     * @param updateSupport 是否更新
+     * @return 结果
+     */
+    @Override
+    public String importData(List<RegionDevelop> dataList, boolean updateSupport) {
+        BulkImportService<RegionDevelop> importService = new BulkImportService<RegionDevelop>() {
+            @Override
+            protected Long checkExistingItem(RegionDevelop item) {
+                RegionDevelop RegionDevelop = regionDevelopMapper.selectRegionDevelopByTitle(item.getTitle());
+                return RegionDevelop == null ? 0L : RegionDevelop.getId();
+            }
+
+            @Override
+            protected boolean updateItem(RegionDevelop item, Long id) {
+                item.setId(id);
+                item.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
+                item.setUpdateTime(DateUtils.getNowDate());
+                return regionDevelopMapper.updateRegionDevelop(item) > 0;
+            }
+
+            @Override
+            protected boolean executeBatch(List<RegionDevelop> batchDataList) {
+                return regionDevelopMapper.insertRegionDevelopDataList(batchDataList) > 0;
+            }
+
+            @Override
+            protected String getItemTitle(RegionDevelop item) {
+                return item.getTitle();
+            }
+        };
+
+        return importService.importData(dataList, updateSupport);
+    }
+
+    /**
      * 修改东南亚地区发展报告
      *
      * @param regionDevelop 东南亚地区发展报告
@@ -93,41 +138,179 @@ public class RegionDevelopServiceImpl implements IRegionDevelopService {
         return regionDevelopMapper.deleteRegionDevelopById(id);
     }
 
+    // 从文件路径中获取文件扩展名
+    private String getFileExtensionFromPath(String filePath) {
+        int dotIndex = filePath.lastIndexOf(".");
+        if (dotIndex >= 0 && dotIndex < filePath.length() - 1) {
+            return filePath.substring(dotIndex + 1).toLowerCase();
+        }
+        System.out.println("10." + dotIndex);
+        return "";
+    }
+
+    // 根据文件路径和指定的文件夹名称获取子文件夹路径
+    private String getSubFolderPath(String filePath, String folderName) {
+        int index = filePath.lastIndexOf(File.separator + folderName + File.separator);
+        if (index != -1) {
+            return filePath.substring(0, index);
+        }
+        return filePath;
+    }
+
+    //删除
+    public boolean deleteFile(Long ids) {
+        // 根据ID查询文件信息
+        RegionDevelop file = regionDevelopMapper.selectRegionDevelopById(ids);
+        System.out.println("4." + file);
+        if (file == null) {
+            return false; // 文件不存在,删除失败
+        }
+
+        String oldPath = file.getPath();
+        Long count = file.getCount();
+
+        if (oldPath != null) {
+            String filePath = RuoYiConfig.getUploadPath();
+
+            //由于在RuoYiConfig.getUploadPath()中带有upload导致文件搜索失败,所以去除
+            String keyword = "/upload";
+            int endIndex = filePath.indexOf(keyword);
+            if (endIndex != -1) {
+                filePath = filePath.substring(0, (filePath.length()-7));
+            }
+
+            String deletaPath = filePath + StringUtils.substringAfter(oldPath, Constants.RESOURCE_PREFIX);
+            System.out.println("5." + deletaPath);
+            if (deleteFileRecursive(deletaPath, count)) {
+                // 执行特定文件夹删除操作
+                String fileExtension = getFileExtensionFromPath(deletaPath);
+                if (fileExtension.equalsIgnoreCase("pdf")) {
+                    String subFolderPath = getSubFolderPath(deletaPath, "pdf");
+                    System.out.println("8." + subFolderPath);
+                    deleteFolder(subFolderPath); // 修改这一行
+                } else if (fileExtension.equalsIgnoreCase("doc") || fileExtension.equalsIgnoreCase("docx")) {
+                    String subFolderPath = getSubFolderPath(deletaPath, "word");
+                    System.out.println("9." + subFolderPath);
+                    deleteFolder(subFolderPath); // 修改这一行
+                }
+
+                // 删除数据库中的文件记录
+                int deleteCount = regionDevelopMapper.deleteRegionDevelopById(ids);
+                System.out.println("文件删除成功");
+                return true; // 文件删除成功
+            } else {
+                System.out.println("文件删除失败");
+                return false; // 文件删除失败
+            }
+        }
+        return false;
+    }
+
     /**
-     * 导入数据
+     * 删除文件
      *
-     * @param dataList      数据列表
-     * @param updateSupport 是否更新
-     * @return 结果
+     * @param ids 文件
+     * @return
      */
-    @Override
-    public String importData(List<RegionDevelop> dataList, boolean updateSupport) {
-        BulkImportService<RegionDevelop> importService = new BulkImportService<RegionDevelop>() {
-            @Override
-            protected Long checkExistingItem(RegionDevelop item) {
-                RegionDevelop RegionDevelop = regionDevelopMapper.selectRegionDevelopByTitle(item.getTitle());
-                return RegionDevelop == null ? 0L : RegionDevelop.getId();
+    public static boolean deleteFileRecursive(String ids, Long count) {
+        for (String s : deleteFileList(ids, count)){
+            File file = new File(s);
+            System.out.println("11. " + s);
+            if (file.isFile() && file.exists()) {
+                if (!file.delete()){
+                    return false;
+                }
             }
+        }
 
-            @Override
-            protected boolean updateItem(RegionDevelop item, Long id) {
-                item.setId(id);
-                item.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
-                item.setUpdateTime(DateUtils.getNowDate());
-                return regionDevelopMapper.updateRegionDevelop(item) > 0;
-            }
+        return true;
+    }
 
-            @Override
-            protected boolean executeBatch(List<RegionDevelop> batchDataList) {
-                return regionDevelopMapper.insertRegionDevelopDataList(batchDataList) > 0;
-            }
+    /**
+     * 获取要删除的文件列表
+     */
+    public static List<String> deleteFileList(String str, Long count){
+        //获取/前的str
+        String path = "";
+        // 查找最后一个 '/' 的索引
+        int lastSlashIndex = str.lastIndexOf('/');
+        // 确保找到 '/' 并且 '/' 不是第一个字符
+        if (lastSlashIndex > 0 && lastSlashIndex < str.length() - 1) {
+            // 获取 '/' 前面的字符
+            path = str.substring(0, lastSlashIndex);
+        }
+        // 获取文件名
+        String fileName = str.substring(lastSlashIndex+1);
 
-            @Override
-            protected String getItemTitle(RegionDevelop item) {
-                return item.getTitle();
+        String[] strings = splitFileName(fileName);
+        List<String> list = new ArrayList<>();
+        int i = 0;
+        // 如果文件不从0开始
+        if (!strings[1].equals("00")){
+            i = 1;
+            count++;
+        }
+        for (; i < count; i++){
+            String fileNumber = "";
+            System.out.println(strings[1]);
+            if (i < 100){
+                fileNumber = String.format("%02d", i);
+            }else {
+                fileNumber = String.valueOf(i);
             }
-        };
 
-        return importService.importData(dataList, updateSupport);
+            String filename = path + "/" + strings[0] + "_" + fileNumber + "." + strings[2];
+            System.out.println("filename"+filename);
+            list.add(filename);
+        }
+        return list;
+    }
+
+    /**
+     * 分解格式为 xxx_00.jpg 的字符串
+     *
+     * @param fileName 要处理的字符串
+     * @return 分解后的字符串数组,其中包含_前面的部分,_和.之间的部分,以及.后面的部分
+     */
+    public static String[] splitFileName(String fileName) {
+        // 找到 '_' 和 '.' 的索引
+        int underscoreIndex = fileName.indexOf('_');
+        int dotIndex = fileName.indexOf('.');
+
+        // 检查索引有效性
+        if (underscoreIndex == -1 || dotIndex == -1 || underscoreIndex >= dotIndex) {
+            throw new IllegalArgumentException("字符串格式不正确");
+        }
+
+        // 获取 _ 前面的部分
+        String partBeforeUnderscore = fileName.substring(0, underscoreIndex);
+
+        // 获取 _ 和 . 之间的部分
+        String partBetweenUnderscoreAndDot = fileName.substring(underscoreIndex + 1, dotIndex);
+
+        // 获取 . 后面的部分
+        String partAfterDot = fileName.substring(dotIndex + 1);
+
+        return new String[] { partBeforeUnderscore, partBetweenUnderscoreAndDot, partAfterDot };
+    }
+
+
+    // 递归删除文件夹及其内容
+    private void deleteFolder(String filePath) {
+        File folder = new File(filePath);
+        System.out.println("9." + folder);
+        if (folder.exists()) {
+            File[] files = folder.listFiles();
+            if (files != null) {
+                for (File file : files) {
+                    if (file.isDirectory()) {
+                        deleteFolder(file.getPath()); // 使用完整的文件夹路径
+                    } else {
+                        file.delete();
+                    }
+                }
+                folder.delete();
+            }
+        }
     }
 }