FileController.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.chuanghai.h3c_reporting.controller;
  2. import com.chuanghai.h3c_reporting.common.exception.BizCodeEnume;
  3. import com.chuanghai.h3c_reporting.common.exception.RRException;
  4. import com.chuanghai.h3c_reporting.common.utils.CommonResult;
  5. import org.apache.ibatis.annotations.Param;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.web.bind.annotation.PostMapping;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import java.io.File;
  12. import java.io.IOException;
  13. import java.util.ArrayList;
  14. import java.util.Arrays;
  15. import java.util.List;
  16. import java.util.UUID;
  17. /**
  18. * @author 27951
  19. * @version 1.0
  20. * @description: TODO 文件处理
  21. * @date 2022/7/27 14:30
  22. */
  23. @RestController
  24. @RequestMapping("/file")
  25. public class FileController {
  26. @Value("${file.imgPath}")
  27. private String imgPath;
  28. @Value("${file.imgPathDown}")
  29. private String imgPathDown;
  30. /**
  31. * 获取文件路径链接
  32. */
  33. @PostMapping("/fileUpDown")
  34. public CommonResult<String> fileUpDown(@Param("file") MultipartFile file[]) {
  35. List<MultipartFile> fileList = Arrays.asList(file);
  36. List<String> files = new ArrayList<>();
  37. fileList.forEach(file1 -> {
  38. try {
  39. //获取文件名
  40. String fileName = file1.getOriginalFilename();
  41. //获取文件后缀名。
  42. assert fileName != null;
  43. String suffixName = fileName.substring(fileName.lastIndexOf("."));
  44. //为了避免发生文件替换,这里使用了文件名重新生成
  45. fileName = UUID.randomUUID() + suffixName;
  46. // 判断文件后缀名,不符合要求的不保存
  47. if (suffixName.equals(".jpg") || suffixName.equals(".jpeg") || suffixName.equals(".png")) {
  48. file1.transferTo(new File(imgPath, fileName));
  49. files.add(imgPathDown + fileName);
  50. } else {
  51. throw new RRException(BizCodeEnume.FILE_NOT);
  52. }
  53. } catch (IOException e) {
  54. throw new RRException(BizCodeEnume.FILE_UPDOWN_FAIL);
  55. }
  56. });
  57. return CommonResult.ok().setResult(files);
  58. }
  59. }