OssUtils.java 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package com.poteviohealth.cgp.statistics.utils;
  2. import com.aliyun.oss.OSS;
  3. import com.aliyun.oss.OSSClientBuilder;
  4. import com.poteviohealth.cgp.common.model.VaultsResponse;
  5. import com.poteviohealth.cgp.common.utils.CgpTool;
  6. import lombok.extern.log4j.Log4j2;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.stereotype.Component;
  9. import org.springframework.web.multipart.MultipartFile;
  10. /**
  11. * 阿里云图片上传工具类
  12. * @author Qin
  13. */
  14. @Component
  15. @Log4j2
  16. public class OssUtils {
  17. @Value("${aliyun.oss.accessKeyId}")
  18. private String accessKeyId;
  19. @Value("${aliyun.oss.accessKeySecret}")
  20. private String secretAccessKey;
  21. @Value("${aliyun.oss.endpoint}")
  22. private String endPoint;
  23. @Value("${aliyun.oss.bucketName}")
  24. private String bucketName;
  25. @Value("${aliyun.oss.dir}")
  26. private String dir;
  27. public VaultsResponse<String> uploadOneFile(MultipartFile dto,Long orderId) {
  28. // 创建OSSClient实例。
  29. OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
  30. try {
  31. log.info("fileName==="+dto.getOriginalFilename());
  32. //设置文件名
  33. Integer pos = dto.getOriginalFilename().lastIndexOf('.');
  34. String suffix = "";
  35. if (pos != -1) {
  36. suffix = dto.getOriginalFilename().substring(pos);
  37. }
  38. String fileName = dir+"S"+orderId+"N-"+ CgpTool.generateUUID() +suffix;
  39. // 创建PutObject请求。
  40. ossClient.putObject(bucketName, fileName, dto.getInputStream());
  41. String url = "https://" + bucketName + "." + endPoint + "/" + fileName;
  42. // System.out.println(url);
  43. return VaultsResponse.success(url);
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. return null;
  47. } finally {
  48. if (ossClient != null) {
  49. ossClient.shutdown();
  50. }
  51. }
  52. }
  53. public boolean deleteFile(String fileUrl) {
  54. // 创建OSSClient实例。
  55. OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
  56. /** oss删除文件是根据文件完成路径删除的,但文件完整路径中不能包含Bucket名称。
  57. * 比如文件路径为:http://edu-czf.oss-cn-guangzhou.aliyuncs.com/2022/08/abc.jpg",
  58. * 则完整路径就是:2022/08/abc.jpg
  59. */
  60. int begin = ("https://" + bucketName + "." + endPoint + "/").length(); //找到文件路径的开始下标
  61. String deleteUrl = fileUrl.substring(begin);
  62. try {
  63. // 删除文件请求
  64. ossClient.deleteObject(bucketName, deleteUrl);
  65. return true;
  66. } catch (Exception e) {
  67. e.printStackTrace();
  68. return false;
  69. } finally {
  70. if (ossClient != null) {
  71. ossClient.shutdown();
  72. }
  73. }
  74. }
  75. }