UploadController.java 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. package com.loan.system.controller.wechat;
  2. import com.loan.system.config.FileUploadConfig;
  3. import com.loan.system.domain.entity.Document;
  4. import com.loan.system.domain.enums.ExceptionEnum;
  5. import com.loan.system.domain.pojo.Result;
  6. import com.loan.system.domain.vo.DocumentVO;
  7. import com.loan.system.service.DocumentService;
  8. import com.loan.system.utils.ResultUtil;
  9. import io.swagger.annotations.Api;
  10. import io.swagger.annotations.ApiOperation;
  11. import org.apache.commons.io.FilenameUtils;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.security.access.prepost.PreAuthorize;
  14. import org.springframework.util.ObjectUtils;
  15. import org.springframework.web.bind.annotation.*;
  16. import org.springframework.web.multipart.MultipartFile;
  17. import javax.servlet.http.HttpServletResponse;
  18. import java.io.*;
  19. import java.net.URLEncoder;
  20. import java.nio.file.Files;
  21. import java.nio.file.Path;
  22. import java.nio.file.Paths;
  23. import java.nio.file.StandardCopyOption;
  24. import java.time.LocalDateTime;
  25. import java.time.format.DateTimeFormatter;
  26. import java.util.*;
  27. @RestController
  28. @RequestMapping("/wechat/file")
  29. @Api(tags = "文件处理接口")
  30. public class UploadController {
  31. @Autowired
  32. private DocumentService fileService;
  33. @Autowired
  34. private FileUploadConfig config;
  35. /** 上传文件(支持任意类型,只要在白名单内) */
  36. @PostMapping("/upload/{caseId}/{type}")
  37. @ApiOperation("文件上传")//若合同不是统一提交,则合同1,合同2,合同3
  38. public Result uploadFile(@PathVariable("caseId") Long caseId,@PathVariable("type") String fileType,@RequestParam MultipartFile file,@RequestParam Map<String , String> isDelete) throws IOException{
  39. Iterator<Map.Entry<String, String>> iterator = isDelete.entrySet().iterator();
  40. while (iterator.hasNext()) {
  41. Map.Entry<String, String> entry = iterator.next();
  42. System.out.println(entry.getKey());
  43. Long id = Long.parseLong(entry.getKey());
  44. System.out.println(entry.getValue());
  45. Integer value = Integer.parseInt(entry.getValue());
  46. Document document = fileService.findById(id);
  47. if (ObjectUtils.isEmpty( document))
  48. break;
  49. if( value!= 0 ){
  50. fileService.deleteFileById(id);
  51. //删除本地文件
  52. deleteFile1(document.getFilePath());
  53. }
  54. }
  55. if (file.isEmpty())
  56. return ResultUtil.error(ExceptionEnum.FILE_IS_EMPTY);
  57. String originalName = file.getOriginalFilename();
  58. String ext = FilenameUtils.getExtension(originalName).toLowerCase(Locale.ROOT);
  59. // 从配置中读取允许的扩展名
  60. Set<String> allowed = config.getAllowedExtensions();
  61. if (!allowed.contains(ext)) {
  62. ResultUtil.error(ExceptionEnum.FILE_UPLOAD_TYPE_NOT_DEFINED);
  63. }
  64. String newFileName = String.format("%d-%s-%s.%s", caseId, fileType, UUID.randomUUID(), ext);;
  65. // 生成新的文件名
  66. // 创建目录
  67. File uploadDir = new File(config.getUploadDir(), caseId + "/" + fileType);
  68. System.out.println(uploadDir);
  69. System.out.println(newFileName);
  70. if (!uploadDir.exists() && !uploadDir.mkdirs()) {
  71. return ResultUtil.error(ExceptionEnum.DIRECTORY_CREATE_ERROR);
  72. }
  73. // 使用NIO复制流,稳定性更好
  74. File destFile = new File(uploadDir, newFileName);
  75. try (InputStream in = file.getInputStream()) {
  76. System.out.println(destFile.toPath());
  77. Files.copy(in, destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
  78. }
  79. Document document = new Document();
  80. document.setCaseId(caseId);
  81. document.setFileName(newFileName);
  82. document.setOriginName(originalName);
  83. document.setFilePath(destFile.getPath());
  84. document.setFileSize(file.getSize());
  85. document.setDocType(ext);
  86. document.setDictType(fileType); // 简单转换为整数
  87. document.setIsDelete( false);
  88. document.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
  89. document.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
  90. DocumentVO documentVO = fileService.uploadFile(document);
  91. return ResultUtil.success("上传成功",documentVO);
  92. }
  93. private void deleteFile1(String filePath) {
  94. if (filePath == null || filePath.isEmpty()) {
  95. return;
  96. }
  97. try {
  98. Path path = Paths.get(filePath);
  99. boolean deleted = Files.deleteIfExists(path);
  100. if (deleted) {
  101. System.out.println("文件删除成功: " + filePath);
  102. } else {
  103. System.out.println("文件不存在或已被删除: " + filePath);
  104. }
  105. } catch (IOException e) {
  106. System.err.println("删除文件时发生错误: " + e.getMessage());
  107. e.printStackTrace();
  108. }
  109. }
  110. /** 下载文件 */
  111. @GetMapping("/download/{fileName}")
  112. @ApiOperation("文件下载")
  113. public void downloadFile(@PathVariable String fileName, HttpServletResponse response)throws IOException{
  114. File file = new File(config.getUploadDir(), fileName);
  115. if (!file.exists()) {
  116. response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
  117. return;
  118. }
  119. response.setContentType(Files.probeContentType(file.toPath()));
  120. response.setHeader("Content-Disposition",
  121. "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
  122. try (InputStream in = new FileInputStream(file);
  123. OutputStream out = response.getOutputStream()) {
  124. byte[] buffer = new byte[8192];
  125. int len;
  126. while ((len = in.read(buffer)) != -1) {
  127. out.write(buffer, 0, len);
  128. }
  129. }
  130. }
  131. /** 删除文件 */
  132. @DeleteMapping("/delete/{caseId}/{type}")
  133. @ApiOperation("文件删除")
  134. public Result deleteFileByFileName(@RequestParam String fileName ,@PathVariable Long caseId, @PathVariable String fileType) {
  135. String newUploadDir = config.getUploadDir() + caseId + "/" + fileType;
  136. File file = new File(newUploadDir, fileName);
  137. if (!file.exists())
  138. return ResultUtil.error(ExceptionEnum.FILE_NOT_EXIST);
  139. boolean isDelete = file.delete();
  140. if (!isDelete)
  141. return ResultUtil.error(ExceptionEnum.FILE_DELETE_ERROR);
  142. return ResultUtil.success("文件删除成功");
  143. }
  144. /** 删除文件 */
  145. /** 删除文件 */
  146. private void deleteFile(Long caseId, String fileType) {
  147. // 构造待删除文件所在的目录路径
  148. File uploadDir = new File(config.getUploadDir(), caseId + "/" + fileType);
  149. if (!uploadDir.exists()) {
  150. System.out.println("Directory does not exist: " + uploadDir.getAbsolutePath());
  151. return; // 目录不存在,直接返回
  152. }
  153. // 获取目录下所有文件
  154. File[] files = uploadDir.listFiles();
  155. if (files == null || files.length == 0) {
  156. System.out.println("No files to delete in directory: " + uploadDir.getAbsolutePath());
  157. return; // 没有文件需要删除
  158. }
  159. boolean allDeleted = true;
  160. for (File file : files) {
  161. System.out.println("Attempting to delete file: " + file.getAbsolutePath());
  162. if (!file.delete()) { // 尝试删除每个文件
  163. allDeleted = false; // 如果有文件未能成功删除,则标记为false
  164. System.out.println("Failed to delete file: " + file.getAbsolutePath());
  165. } else {
  166. System.out.println("Successfully deleted file: " + file.getAbsolutePath());
  167. }
  168. }
  169. if (!allDeleted) {
  170. System.out.println("Failed to delete some files in directory: " + uploadDir.getAbsolutePath());
  171. } else {
  172. System.out.println("All files deleted successfully in directory: " + uploadDir.getAbsolutePath());
  173. }
  174. }
  175. // @PostMapping("save/{caseId}/{type}")
  176. // public Result saveFile(@PathVariable("caseId") Long caseId,@PathVariable("type") String type,@RequestParam String fileName){
  177. // return ResultUtil.success();
  178. // }
  179. }