UploadService.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package com.fdkankan.sale.service.impl;
  2. import com.fdkankan.fyun.face.FYunFileServiceInterface;
  3. import com.fdkankan.sale.common.CacheUtil;
  4. import com.fdkankan.sale.common.FilePath;
  5. import com.fdkankan.sale.common.ResultCode;
  6. import com.fdkankan.sale.exception.BusinessException;
  7. import org.apache.commons.lang3.StringUtils;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.stereotype.Service;
  11. import org.springframework.web.multipart.MultipartFile;
  12. import javax.annotation.Resource;
  13. import java.io.File;
  14. import java.util.UUID;
  15. @Service
  16. public class UploadService {
  17. @Autowired
  18. FYunFileServiceInterface fYunFileServiceInterface;
  19. public String uploadFile(MultipartFile file) {
  20. if(file.isEmpty()){
  21. throw new BusinessException(ResultCode.UPLOAD_FILE_NO_EXIST);
  22. }
  23. if(file.getSize()>10 * 1024 * 1024 * 100){
  24. System.out.println(file.getSize());
  25. throw new BusinessException(ResultCode.UPLOAD_FILE_TO_LONG);
  26. }
  27. //获取文件名
  28. String fileName = file.getOriginalFilename();
  29. if(StringUtils.isEmpty(fileName)){
  30. throw new BusinessException(ResultCode.UPLOAD_FILE_NO_EXIST);
  31. }
  32. File localFile = null;
  33. try {
  34. //获取文件后缀名
  35. String suffixName = fileName.substring(fileName.lastIndexOf("."));
  36. //重新生成文件名
  37. fileName = UUID.randomUUID().toString().replace("-","") ;
  38. localFile = File.createTempFile(fileName ,suffixName);
  39. //localFile = new File(String.format(FilePath.file_path,CacheUtil.environment,fileName +suffixName));
  40. if(!localFile.getParentFile().exists()){
  41. localFile.mkdirs();
  42. }
  43. file.transferTo(localFile);
  44. String ossPath = String.format(FilePath.oss_file_path,CacheUtil.environment, fileName + suffixName);
  45. fYunFileServiceInterface.uploadFile(localFile.getPath(),ossPath);
  46. return CacheUtil.host + ossPath;
  47. }catch (Exception e){
  48. e.printStackTrace();
  49. }finally {
  50. if(localFile!=null){
  51. localFile.delete(); //退出删除,后续需要使用文件
  52. }
  53. }
  54. return null;
  55. }
  56. public void deleteOssUrl(String path) {
  57. try {
  58. fYunFileServiceInterface.deleteFile(path);
  59. }catch (Exception e){
  60. e.printStackTrace();
  61. }
  62. }
  63. }