当前位置:   article > 正文

腾讯云COS和阿里云OSS在Springboot中的使用_springboot继承腾讯oss

springboot继承腾讯oss

引言:之前本来是用OSS做存储的,但是上线小程序发现OSS貌似消费比COS多一些,所以之前做了技术搬迁,最近想起,打算做个笔记记录一下,这里省去在阿里云注册OSS或腾讯云中注册COS应用了。

一、OSS

1、配置yml
  1. qupai:
  2. alioss:
  3. endpoint: ${qupai.alioss.endpoint}
  4. access-key-id: ${qupai.alioss.access-key-id}
  5. access-key-secret: ${qupai.alioss.access-key-secret}
  6. bucket-name: ${qupai.alioss.bucket-name}

2、编写配置类读取yml配置
  1. @Component
  2. @ConfigurationProperties(prefix = "qupai.alioss")
  3. @Data
  4. public class AliOssProperties {
  5. private String endpoint;
  6. private String accessKeyId;
  7. private String accessKeySecret;
  8. private String bucketName;
  9. }

3、编写COS工具类
  1. @Data
  2. @AllArgsConstructor
  3. @Slf4j
  4. public class AliOssUtil {
  5. private String endpoint;
  6. private String accessKeyId;
  7. private String accessKeySecret;
  8. private String bucketName;
  9. /**
  10. * 文件上传
  11. *
  12. * @param bytes
  13. * @param objectName
  14. * @return
  15. */
  16. public String upload(byte[] bytes, String objectName) {
  17. // 创建OSSClient实例。
  18. OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
  19. try {
  20. // 创建PutObject请求。
  21. ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
  22. } catch (OSSException oe) {
  23. System.out.println("Caught an OSSException, which means your request made it to OSS, "
  24. + "but was rejected with an error response for some reason.");
  25. System.out.println("Error Message:" + oe.getErrorMessage());
  26. System.out.println("Error Code:" + oe.getErrorCode());
  27. System.out.println("Request ID:" + oe.getRequestId());
  28. System.out.println("Host ID:" + oe.getHostId());
  29. } catch (ClientException ce) {
  30. System.out.println("Caught an ClientException, which means the client encountered "
  31. + "a serious internal problem while trying to communicate with OSS, "
  32. + "such as not being able to access the network.");
  33. System.out.println("Error Message:" + ce.getMessage());
  34. } finally {
  35. if (ossClient != null) {
  36. ossClient.shutdown();
  37. }
  38. }
  39. //文件访问路径规则 https://BucketName.Endpoint/ObjectName
  40. StringBuilder stringBuilder = new StringBuilder("https://");
  41. stringBuilder
  42. .append(bucketName)
  43. .append(".")
  44. .append(endpoint)
  45. .append("/")
  46. .append(objectName);
  47. log.info("文件上传到:{}", stringBuilder.toString());
  48. return stringBuilder.toString();
  49. }
  50. }

4、声明配置类在程序开始时交给bean对象注入
  1. /**
  2. * 配置类,用于创建AliOssUtils对象
  3. */
  4. @Configuration//声明配置类
  5. @Slf4j
  6. public class OssConfiguration {
  7. @Bean//程序开始时交给bean对象注入
  8. @ConditionalOnMissingBean//保证spring容器里面只有一个utils对象(当没有这个bean对象再去创建,有就没必要去创建了)
  9. public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
  10. log.info("开始创建阿里云文件上传工具类对象: {}",aliOssProperties);
  11. return new AliOssUtil(aliOssProperties.getEndpoint(),
  12. aliOssProperties.getAccessKeyId(),
  13. aliOssProperties.getAccessKeySecret(),
  14. aliOssProperties.getBucketName());
  15. }
  16. }

5、在接口中使用
  1. /**
  2. * 通用接口
  3. */
  4. @RestController("adminCommonController")
  5. @RequestMapping("/admin/common")
  6. @Tag(name = "通用接口")
  7. @Slf4j
  8. public class CommonController {
  9. @Resource
  10. private AliOssUtil aliOssUtil;
  11. /**
  12. * 文件上传
  13. * @param file
  14. * @return
  15. */
  16. @PostMapping("/upload")
  17. @Operation(summary="文件上传")
  18. public Result<String> upload(MultipartFile file) {
  19. log.info("上传文件:{}", file);
  20. //file.getBytes(),file对象转成的一个数组,objectName文件名通过uuid来生成
  21. try {
  22. //原始文件名
  23. String originalFilename = file.getOriginalFilename();
  24. //截取元素文件名的后缀,dfdfdf.png
  25. String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
  26. //构造新的文件名称
  27. String objectName=UUID.randomUUID().toString()+extension;
  28. //文件的请求路径
  29. String filePath = aliOssUtil.upload(file.getBytes(), objectName);
  30. return Result.success(filePath);
  31. } catch (IOException e) {
  32. log.error("文件上传失败: {}", e);
  33. }
  34. return Result.error(MessageConstant.UPLOAD_FAILED);
  35. }
  36. }

二、COS

1、配置yml
  1. quick:
  2. tencentcos:
  3. appid: ${quick.tencentcos.appid}
  4. secret-id: ${quick.tencentcos.secret-id}
  5. secret-key: ${quick.tencentcos.secret-key}
  6. bucket-name: ${quick.tencentcos.bucket-name}
  7. cos-path: ${quick.tencentcos.cos-path}
  8. region: ${quick.tencentcos.region}

 

2、编写配置类读取yml配置
  1. /*
  2. * @读取yml配置
  3. */
  4. @Component
  5. @Data
  6. @ConfigurationProperties(prefix = "quick.tencentcos")
  7. public class TencentCosProperties {
  8. private String appid;
  9. private String secretId;
  10. private String secretKey;
  11. private String bucketName;
  12. private String cosPath;
  13. private String region;
  14. }

3、编写COS工具类
  1. @Data
  2. @AllArgsConstructor
  3. @Slf4j
  4. public class TencentCosUtil {
  5. // 腾讯云cos 配置信息
  6. private String appid;
  7. private String secretId;
  8. private String secretKey;
  9. private String bucketName;
  10. private String cosPath;
  11. private String region;
  12. /**
  13. * 1.调用静态方法getCosClient()就会获得COSClient实例
  14. * 2.本方法根据永久密钥初始化 COSClient的,官方是不推荐,官方推荐使用临时密钥,是可以限制密钥使用权限,创建cred时有些区别
  15. *
  16. * @return COSClient实例
  17. */
  18. public COSClient getCosClient() {
  19. // 1 初始化用户身份信息(secretId, secretKey)
  20. COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
  21. // 2.1 设置存储桶的地域(上文获得)
  22. Region region_new = new Region(region);
  23. ClientConfig clientConfig = new ClientConfig(region_new);
  24. // 2.2 使用https协议传输
  25. clientConfig.setHttpProtocol(HttpProtocol.https);
  26. // 3 生成 cos 客户端
  27. // 返回COS客户端
  28. return new COSClient(cred, clientConfig);
  29. }
  30. /**
  31. * 上传文件
  32. *
  33. * @param file 上传的文件
  34. * @return 返回文件的url
  35. */
  36. public String upLoadFile(MultipartFile file) {
  37. try {
  38. // 获取上传的文件的输入流
  39. InputStream inputStream = file.getInputStream();
  40. // 避免文件覆盖,获取文件的原始名称,如123.jpg,然后通过截取获得文件的后缀,也就是文件的类型
  41. String originalFilename = file.getOriginalFilename();
  42. // 获取文件的类型
  43. String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
  44. // 使用UUID工具 创建唯一名称,放置文件重名被覆盖,在拼接上上命令获取的文件类型
  45. String fileName = UUID.randomUUID().toString() + fileType;
  46. // 指定文件上传到 COS 上的路径,即对象键最终文件会传到存储桶名字中的images文件夹下的fileName名字
  47. String key = "/images/" + fileName;
  48. // 创建上传Object的Metadata
  49. ObjectMetadata objectMetadata = new ObjectMetadata();
  50. // - 使用输入流存储,需要设置请求长度
  51. objectMetadata.setContentLength(inputStream.available());
  52. // - 设置缓存
  53. objectMetadata.setCacheControl("no-cache");
  54. // - 设置Content-Type
  55. objectMetadata.setContentType(fileType);
  56. // 上传文件
  57. PutObjectResult putResult = getCosClient().putObject(bucketName, key, inputStream, objectMetadata);
  58. // 创建文件的网络访问路径
  59. String url = cosPath + key;
  60. // 关闭 cosClient,并释放 HTTP 连接的后台管理线程
  61. getCosClient().shutdown();
  62. return url;
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. // 发生IO异常、COS连接异常等,返回空
  66. return null;
  67. }
  68. }
  69. }

4、声明配置类在程序开始时交给bean对象注入
  1. /**
  2. * 配置类,用于创建AliOssUtils对象
  3. */
  4. @Configuration//声明配置类
  5. @Slf4j
  6. public class CosConfiguration {
  7. @Bean//程序开始时交给bean对象注入
  8. @ConditionalOnMissingBean//保证spring容器里面只有一个utils对象(当没有这个bean对象再去创建,有就没必要去创建了)
  9. public TencentCosUtil tencentCosUtil(TencentCosProperties tencentCosProperties){
  10. log.info("开始创建腾讯云文件上传工具类对象: {}",tencentCosProperties);
  11. return new TencentCosUtil(tencentCosProperties.getAppid(),
  12. tencentCosProperties.getSecretId(),
  13. tencentCosProperties.getSecretKey(),
  14. tencentCosProperties.getBucketName(),
  15. tencentCosProperties.getCosPath(),
  16. tencentCosProperties.getRegion());
  17. }
  18. }

5、在接口中使用
  1. @Resource
  2. private TencentCosUtil tencentCosUtil;
  3. /**
  4. * 文件上传
  5. */
  6. @PostMapping("/upload")
  7. //@ApiOperation("文件上传")
  8. @Operation(summary = "文件上传")
  9. public Result<String> upload(MultipartFile file) {
  10. log.info("上传文件:{}", file);
  11. log.info("正在上传,文件名{}",file.getOriginalFilename());
  12. String url = tencentCosUtil.upLoadFile(file);
  13. log.info("文件的Url:{}",url);
  14. return Result.success(url);
  15. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/993380
推荐阅读
相关标签
  

闽ICP备14008679号