FileController.java 4.2 KB

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