UploadController.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package com.travel.controller;
  2. import cn.hutool.core.date.DateUtil;
  3. import com.travel.util.ossFileUtil;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.CrossOrigin;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. import org.springframework.web.multipart.MultipartFile;
  10. import java.text.SimpleDateFormat;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. import java.util.Random;
  14. /**
  15. * 上传接口
  16. */
  17. @Controller
  18. @RequestMapping("upload")
  19. @Slf4j
  20. @CrossOrigin
  21. public class UploadController {
  22. /**
  23. * 上传
  24. * @param file 文件
  25. * @return 返回结果
  26. */
  27. @RequestMapping(value = "/uploadFile")
  28. @ResponseBody
  29. public Map<String, Object> upload(MultipartFile file) {
  30. Map<String, Object> map = new HashMap<>();
  31. if (!file.isEmpty()) {
  32. try {
  33. SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
  34. String suffix = file.getOriginalFilename()
  35. .substring(file.getOriginalFilename().lastIndexOf("."));
  36. // 生成文件名称
  37. String nameSuffix = file.getOriginalFilename()
  38. .substring(0, file.getOriginalFilename().lastIndexOf("."))
  39. .replaceAll(" ", "_").replaceAll(",", "")
  40. + format.format(DateUtil.date())
  41. + new Random().nextInt(1000) + suffix;
  42. //上传原始图片到阿里云
  43. return ossFileUtil.uploadAliyun(file, nameSuffix);
  44. } catch (Exception e) {
  45. log.error("上传附件错误" + e.getMessage());
  46. map.put("erroMsg", "系统未知错误");
  47. map.put("msg", "500");
  48. }
  49. } else {
  50. map.put("msg", "500");
  51. map.put("erroMsg", "文件不能为空");
  52. }
  53. return map;
  54. }
  55. /**
  56. * 删除文件
  57. * @param fileName 文件名称
  58. * @return 返回结果
  59. */
  60. @RequestMapping(value = "/delUpload")
  61. @ResponseBody
  62. public Map<String, Object> delUpload(String fileName) {
  63. Map<String, Object> map = new HashMap<>();
  64. if (!fileName.isEmpty()) {
  65. try {
  66. //删除文件
  67. return ossFileUtil.delUploadAliyun(fileName);
  68. } catch (Exception e) {
  69. log.error("上传附件错误" + e.getMessage());
  70. map.put("erroMsg", "系统未知错误");
  71. map.put("msg", "500");
  72. }
  73. } else {
  74. map.put("msg", "500");
  75. map.put("erroMsg", "文件不能为空");
  76. }
  77. return map;
  78. }
  79. }