UploadController.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package com.fdkankan.fusion.controller;
  2. import com.fdkankan.common.constant.ErrorCode;
  3. import com.fdkankan.common.exception.BusinessException;
  4. import com.fdkankan.common.response.ResultData;
  5. import com.fdkankan.fusion.common.ResultCode;
  6. import com.fdkankan.fyun.oss.UploadToOssUtil;
  7. import org.apache.commons.lang3.StringUtils;
  8. import org.springframework.beans.factory.annotation.Value;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  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 javax.annotation.Resource;
  15. import java.io.File;
  16. import java.util.UUID;
  17. @RestController
  18. @RequestMapping("/upload")
  19. public class UploadController {
  20. @Resource
  21. private UploadToOssUtil uploadToOssUtil;
  22. @Value("${upload.file-path}")
  23. private String filePath;
  24. @Value("${upload.query-path}")
  25. private String queryPath;
  26. @PostMapping("/file")
  27. public ResultData file(@RequestParam(required = false) MultipartFile file) throws Exception {
  28. if(file.isEmpty()){
  29. throw new BusinessException(ResultCode.UPLOAD_FILE_NO_EXIST.code,ResultCode.UPLOAD_FILE_NO_EXIST.msg);
  30. }
  31. if(file.getSize()>10 * 1024 * 1024 * 100){
  32. System.out.println(file.getSize());
  33. throw new BusinessException(ResultCode.UPLOAD_FILE_TO_LONG.code,ResultCode.UPLOAD_FILE_TO_LONG.msg);
  34. }
  35. //获取文件名
  36. String fileName = file.getOriginalFilename();
  37. if(StringUtils.isEmpty(fileName)){
  38. throw new BusinessException(ResultCode.UPLOAD_FILE_NO_EXIST.code,ResultCode.UPLOAD_FILE_NO_EXIST.msg);
  39. }
  40. //获取文件后缀名
  41. String suffixName = fileName.substring(fileName.lastIndexOf("."));
  42. //重新生成文件名
  43. fileName = UUID.randomUUID().toString().replace("-","");
  44. File localFile = File.createTempFile(fileName,suffixName);
  45. file.transferTo(localFile);
  46. String path = localFile.getPath();
  47. uploadToOssUtil.upload(path,filePath + fileName + suffixName);
  48. if(!uploadToOssUtil.existKey(filePath + fileName + suffixName)){
  49. throw new BusinessException(ResultCode.UPLOAD_ERROR.code,ResultCode.UPLOAD_ERROR.msg);
  50. }
  51. return ResultData.ok( queryPath + filePath + fileName + suffixName);
  52. }
  53. }