| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- package com.poteviohealth.cgp.statistics.utils;
- import com.aliyun.oss.OSS;
- import com.aliyun.oss.OSSClientBuilder;
- import com.poteviohealth.cgp.common.model.VaultsResponse;
- import com.poteviohealth.cgp.common.utils.CgpTool;
- import lombok.extern.log4j.Log4j2;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Component;
- import org.springframework.web.multipart.MultipartFile;
- /**
- * 阿里云图片上传工具类
- * @author Qin
- */
- @Component
- @Log4j2
- public class OssUtils {
- @Value("${aliyun.oss.accessKeyId}")
- private String accessKeyId;
- @Value("${aliyun.oss.accessKeySecret}")
- private String secretAccessKey;
- @Value("${aliyun.oss.endpoint}")
- private String endPoint;
- @Value("${aliyun.oss.bucketName}")
- private String bucketName;
- @Value("${aliyun.oss.dir}")
- private String dir;
- public VaultsResponse<String> uploadOneFile(MultipartFile dto,Long orderId) {
- // 创建OSSClient实例。
- OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
- try {
- log.info("fileName==="+dto.getOriginalFilename());
- //设置文件名
- Integer pos = dto.getOriginalFilename().lastIndexOf('.');
- String suffix = "";
- if (pos != -1) {
- suffix = dto.getOriginalFilename().substring(pos);
- }
- String fileName = dir+"S"+orderId+"N-"+ CgpTool.generateUUID() +suffix;
- // 创建PutObject请求。
- ossClient.putObject(bucketName, fileName, dto.getInputStream());
- String url = "https://" + bucketName + "." + endPoint + "/" + fileName;
- // System.out.println(url);
- return VaultsResponse.success(url);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- } finally {
- if (ossClient != null) {
- ossClient.shutdown();
- }
- }
- }
- public boolean deleteFile(String fileUrl) {
- // 创建OSSClient实例。
- OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
- /** oss删除文件是根据文件完成路径删除的,但文件完整路径中不能包含Bucket名称。
- * 比如文件路径为:http://edu-czf.oss-cn-guangzhou.aliyuncs.com/2022/08/abc.jpg",
- * 则完整路径就是:2022/08/abc.jpg
- */
- int begin = ("https://" + bucketName + "." + endPoint + "/").length(); //找到文件路径的开始下标
- String deleteUrl = fileUrl.substring(begin);
- try {
- // 删除文件请求
- ossClient.deleteObject(bucketName, deleteUrl);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- } finally {
- if (ossClient != null) {
- ossClient.shutdown();
- }
- }
- }
- }
|