FileController.java 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. package cn.keking.web.controller;
  2. import cn.keking.config.ConfigConstants;
  3. import cn.keking.model.ReturnResponse;
  4. import com.fasterxml.jackson.core.JsonProcessingException;
  5. import com.fasterxml.jackson.databind.ObjectMapper;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.util.StreamUtils;
  9. import org.springframework.web.bind.annotation.GetMapping;
  10. import org.springframework.web.bind.annotation.PostMapping;
  11. import org.springframework.web.bind.annotation.RequestParam;
  12. import org.springframework.web.bind.annotation.RestController;
  13. import org.springframework.web.multipart.MultipartFile;
  14. import org.springframework.web.util.HtmlUtils;
  15. import java.io.File;
  16. import java.io.FileOutputStream;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.OutputStream;
  20. import java.nio.charset.StandardCharsets;
  21. import java.util.ArrayList;
  22. import java.util.Arrays;
  23. import java.util.HashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Objects;
  27. /**
  28. * @author yudian-it
  29. * @date 2017/12/1
  30. */
  31. @RestController
  32. public class FileController {
  33. private final Logger logger = LoggerFactory.getLogger(FileController.class);
  34. private final String fileDir = ConfigConstants.getFileDir();
  35. private final String demoDir = "demo";
  36. private final String demoPath = demoDir + File.separator;
  37. @PostMapping("/fileUpload")
  38. public String fileUpload(@RequestParam("file") MultipartFile file) throws JsonProcessingException {
  39. if (ConfigConstants.getFileUploadDisable()) {
  40. return new ObjectMapper().writeValueAsString(ReturnResponse.failure("文件传接口已禁用"));
  41. }
  42. // 获取文件名
  43. String fileName = file.getOriginalFilename();
  44. //判断是否为IE浏览器的文件名,IE浏览器下文件名会带有盘符信息
  45. // escaping dangerous characters to prevent XSS
  46. assert fileName != null;
  47. fileName = HtmlUtils.htmlEscape(fileName, StandardCharsets.UTF_8.name());
  48. // Check for Unix-style path
  49. int unixSep = fileName.lastIndexOf('/');
  50. // Check for Windows-style path
  51. int winSep = fileName.lastIndexOf('\\');
  52. // Cut off at latest possible point
  53. int pos = (Math.max(winSep, unixSep));
  54. if (pos != -1) {
  55. fileName = fileName.substring(pos + 1);
  56. }
  57. // 判断是否存在同名文件
  58. if (existsFile(fileName)) {
  59. return new ObjectMapper().writeValueAsString(ReturnResponse.failure("存在同名文件,请先删除原有文件再次上传"));
  60. }
  61. File outFile = new File(fileDir + demoPath);
  62. if (!outFile.exists() && !outFile.mkdirs()) {
  63. logger.error("创建文件夹【{}】失败,请检查目录权限!", fileDir + demoPath);
  64. }
  65. logger.info("上传文件:{}", fileDir + demoPath + fileName);
  66. try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(fileDir + demoPath + fileName)) {
  67. StreamUtils.copy(in, out);
  68. return new ObjectMapper().writeValueAsString(ReturnResponse.success(null));
  69. } catch (IOException e) {
  70. logger.error("文件上传失败", e);
  71. return new ObjectMapper().writeValueAsString(ReturnResponse.failure());
  72. }
  73. }
  74. @GetMapping("/deleteFile")
  75. public String deleteFile(String fileName) throws JsonProcessingException {
  76. if (fileName.contains("/")) {
  77. fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
  78. }
  79. File file = new File(fileDir + demoPath + fileName);
  80. logger.info("删除文件:{}", file.getAbsolutePath());
  81. if (file.exists() && !file.delete()) {
  82. logger.error("删除文件【{}】失败,请检查目录权限!", file.getPath());
  83. }
  84. return new ObjectMapper().writeValueAsString(ReturnResponse.success());
  85. }
  86. @GetMapping("/listFiles")
  87. public String getFiles() throws JsonProcessingException {
  88. List<Map<String, String>> list = new ArrayList<>();
  89. File file = new File(fileDir + demoPath);
  90. if (file.exists()) {
  91. Arrays.stream(Objects.requireNonNull(file.listFiles())).forEach(file1 -> {
  92. Map<String, String> fileName = new HashMap<>();
  93. fileName.put("fileName", demoDir + "/" + file1.getName());
  94. list.add(fileName);
  95. });
  96. }
  97. return new ObjectMapper().writeValueAsString(list);
  98. }
  99. private boolean existsFile(String fileName) {
  100. File file = new File(fileDir + demoPath + fileName);
  101. return file.exists();
  102. }
  103. }