UploadFileController.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package com.yingyangfly.app.controller;
  2. import com.yingyangfly.common.dto.ResultResponse;
  3. import com.yingyangfly.core.annotation.Log;
  4. import com.yingyangfly.core.enums.OperatorType;
  5. import com.yingyangfly.file.api.FileClient;
  6. import io.swagger.annotations.Api;
  7. import io.swagger.annotations.ApiOperation;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.web.bind.annotation.PostMapping;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RequestParam;
  13. import org.springframework.web.bind.annotation.RestController;
  14. import org.springframework.web.multipart.MultipartFile;
  15. import java.util.Arrays;
  16. import java.util.List;
  17. /**
  18. *
  19. * @author jiangqian
  20. * @date 2023/5/14 0014 14:30
  21. */
  22. @RestController
  23. @RequestMapping("/common")
  24. @Api(tags = "通用接口")
  25. @Slf4j
  26. public class UploadFileController {
  27. @Autowired
  28. private FileClient fileClient;
  29. // 允许上传的文件类型
  30. private static final List<String> ALLOWED_FILE_TYPES = Arrays.asList("png", "jpg", "jpeg", "doc", "xls", "ppt", "mp4", "pdf");
  31. /**
  32. * 通用上传
  33. * file 是文件
  34. * dirName 是文件夹
  35. */
  36. @Log(title = "文件上传",operatorType = OperatorType.MOBILE)
  37. @PostMapping("/upload")
  38. @ApiOperation("文件上传")
  39. public ResultResponse upload(@RequestParam("file") MultipartFile file, @RequestParam("dirName") String dirName) {
  40. if (file.isEmpty()) {
  41. return ResultResponse.fail("文件不能为空");
  42. }
  43. String fileName = file.getOriginalFilename();
  44. if (fileName == null) {
  45. return ResultResponse.fail("文件名不能为空");
  46. }
  47. // 获取文件后缀
  48. String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
  49. // 检查文件类型是否允许
  50. if (!ALLOWED_FILE_TYPES.contains(fileExtension)) {
  51. return ResultResponse.fail("不允许的文件类型: " + fileExtension);
  52. }
  53. String upload = fileClient.upload(file, dirName);
  54. return ResultResponse.success(upload);
  55. }
  56. }