fwq
2022-06-01 a99c1c5221e1e00979dd42b96a4fd2046b9dec98
src/main/java/com/hx/util/COSUtil.java
@@ -63,6 +63,48 @@
      }else{
         imgUrl.append("/"+key);
      }
      cosClient.shutdown();
      return imgUrl.toString();
   }
   /** 后端调用上传图片
    * @param key 上传路径(包括图片名称和和后缀),指定要上传到 COS 上对象键
    * @param localFile
    * @param secretId 用户id
    * @param secretKey 用户秘钥
    * @param regionName 存在域,参考腾讯云
    * @param bucketName 指定要上传到的存储桶
    * @return
    * @throws IOException
    */
   public static String uploadImg(String key,File localFile,String secretId, String secretKey,String regionName,String bucketName) throws IOException {
      // 1 初始化用户身份信息(secretId, secretKey)。
      COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
      // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
      // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
      Region region = new Region(regionName);
      ClientConfig clientConfig = new ClientConfig(region);
      // 3 生成 cos 客户端。
      COSClient cosClient = new COSClient(cred, clientConfig);
      // 设置 Content type, 默认是 application/octet-stream,对于本地文件上传,默认根据本地文件的后缀进行映射
      // ,例如 jpg 文件映射 为image/jpeg对于流式上传 默认是 application/octet-stream
      //objectMetadata.setContentType("application/pdf");
      PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
      PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
      //拼接路径
      StringBuilder imgUrl = new StringBuilder();
      imgUrl.append("https://"+bucketName+".cos."+regionName+".myqcloud.com");
      if(key.startsWith("/")){
         imgUrl.append(key);
      }else{
         imgUrl.append("/"+key);
      }
      cosClient.shutdown();
      return imgUrl.toString();
   }