JeecgBoot扩展腾讯云cos对象存储

Jeecg Boot 扩展腾讯云 cos 对象存储

目前使用的是3.5.3 ,jeecg官方只提供了 minio和阿里云oss的支持。但是顶不住qcloud它便宜啊
果断下单了
果断下单,之后就开始改造一下

1 修改application-xxx.yml

先找到上传类型处,添加一个上传的类型。就叫qcloud吧。

#local、minio、alioss qcloudcos
uploadType: qcloudcos

找到

oss:
  accessKey: ??
  secretKey: ??
  endpoint: oss-cn-beijing.aliyuncs.com
  bucketName: jeecgdev

在下面添加

cos:
  secretId: xx
  secretKey: xx
  endpoint: cos.ap-fulan.myqcloud.com
  bucketName: xxx(appid)

id和key呀啥的 得去腾讯云官网申请了

2 读取配置文件

全局搜索OssConfiguration,找到这个类然后当场复制一个。命名为CosConfiguration

然后将刚才改的yml里面的内容对号入座填上去。

@Configuration
@ConditionalOnProperty(prefix = "jeecg.cos", name = "endpoint")
public class CosConfiguration {

    @Value("${jeecg.cos.endpoint}")
    private String endpoint;
    @Value("${jeecg.cos.secretId}")
    private String secretId;
    @Value("${jeecg.cos.secretKey}")
    private String secretKey;
    @Value("${jeecg.cos.bucketName}")
    private String bucketName;
    @Value("${jeecg.cos.staticDomain:}")
    private String staticDomain;
     @Bean
    public void initCosBootConfiguration() {
        CosBootUtil.setEndPoint(endpoint);
        CosBootUtil.setSecretId(secretId);
        CosBootUtil.setSecretKey(secretKey);
        CosBootUtil.setBucketName(bucketName);//appid
        CosBootUtil.setStaticDomain(staticDomain);
    }

3 建立对应的工具类

把 步骤2 里面看见的OssBootUtil也复制一份

新建一个CosBootUtil的类

先把cos客户端初始化做了

  /**
     * 初始化 cos 客户端
     *
     * @return
     */
    private static COSClient initCos(String endpoint, String secretId, String secretKey) {
        Region region = new Region("ap-hujian");
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(region);
        if (cosClient == null) {
            cosClient = new COSClient(cred, clientConfig);
        }
        if(transferManager==null){
            transferManager=createTransferManager();
        }
        return cosClient;
    }

重点修改一下 upload 方法

public static String upload(MultipartFile file, String fileDir,String customBucket) throws Exception {
     initCos(endPoint,secretId,secretKey);
      //update-begin-author:liusq date:20210809 for: 过滤上传文件类型
      FileTypeFilter.fileTypeFilter(file);
      //update-end-author:liusq date:20210809 for: 过滤上传文件类型
      String filePath = null;
      //初始化临时秘钥
      StringBuilder fileUrl = new StringBuilder();
      String newBucket = bucketName;
      if(oConvertUtils.isNotEmpty(customBucket)){
          newBucket = customBucket;
      }
      try {
          //判断桶是否存在,不存在则创建桶
          if(!cosClient.doesBucketExist(newBucket)){
              CreateBucketRequest createBucketRequest = new CreateBucketRequest(newBucket);
              // 设置 bucket 的权限为 Private(私有读写)、其他可选有 PublicRead(公有读私有写)、PublicReadWrite(公有读写)
             // createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
              try{
                  Bucket bucketResult = cosClient.createBucket(createBucketRequest);
                  log.info("------COS创建存储桶------" + fileUrl);
              } catch (CosServiceException serverException) {
                  serverException.printStackTrace();
              } catch (CosClientException clientException) {
                  clientException.printStackTrace();
              }
          }
          // 获取文件名
          String orgName = file.getOriginalFilename();
          if("" == orgName){
            orgName=file.getName();
          }
          orgName = CommonUtils.getFileName(orgName);
          String fileName = orgName.indexOf(".")==-1
                            ?orgName + "_" + System.currentTimeMillis()
                            :orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
          if (!fileDir.endsWith(SymbolConstant.SINGLE_SLASH)) {
              fileDir = fileDir.concat(SymbolConstant.SINGLE_SLASH);
          }
          //update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
          fileDir=StrAttackFilter.filter(fileDir);
          //update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
          fileUrl = fileUrl.append(fileDir + fileName);

          if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith(CommonConstant.STR_HTTP)) {
              filePath = staticDomain + SymbolConstant.SINGLE_SLASH + fileUrl;
          } else {
              filePath =  newBucket + "." + endPoint + SymbolConstant.SINGLE_SLASH + fileUrl;
          }
          String localfilekey = System.currentTimeMillis()+ orgName.substring(orgName.lastIndexOf(".")).toLowerCase();
          File localFile = null;
          try {
              localFile = new File(localfilekey);
              InputStream inputStream = file.getInputStream();
              FileUtils.copyInputStreamToFile(inputStream, localFile);
              localFile = File.createTempFile(System.currentTimeMillis()+"", orgName.substring(orgName.lastIndexOf(".")).toLowerCase());
              file.transferTo(localFile);
              inputStream.close();
          } catch (Exception e) {
              e.printStackTrace();
          }
          PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileUrl.toString(), localFile);
          PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
          // 设置权限(公开读)
          cosClient.setBucketAcl(newBucket, CannedAccessControlList.PublicRead);
          if (putObjectResult != null) {
              log.info("------COS文件上传成功------" + fileUrl);
          }
          File f = new File(localfilekey);
          if(f.exists()){
              f.delete();
          }
      } catch (Exception e) {
          log.error(e.getMessage(),e);
          return null;
      }
      return fileUrl.toString();
}

4 修改部分判断,添加qcloud分支

全局搜索UPLOAD_TYPE_OSS 一共有两类代码需要修改

 if (CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)) {
     url = MinioUtil.upload(file, bizPath);
 } else if (CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
     url = OssBootUtil.upload(file, bizPath);
 } else if (CommonConstant.UPLOAD_TYPE_COS.equals(uploadType)){
     url = CosBootUtil.upload(file, bizPath);
 }
MultipartFile file = multipartRequest.getFile("file");
if(oConvertUtils.isEmpty(bizPath)){
    if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
        //未指定目录,则用阿里云默认目录 upload
        bizPath = "upload";
        //result.setMessage("使用阿里云文件上传时,必须添加目录!");
        //result.setSuccess(false);
        //return result;
    }else{
        bizPath = "";
    }
}
if(oConvertUtils.isEmpty(bizPath)){
    if(CommonConstant.UPLOAD_TYPE_COS.equals(uploadType)){
        //未指定目录,则用tx云默认目录 upload
        bizPath = "upload";
    }else{
        bizPath = "";
    }
}

搞定!

收工!

开薅!

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值