java腾讯云COS使用

1、项目添加cos-api包:
<dependency>
    <groupId>com.qcloud</groupId>
    <artifactId>cos_api</artifactId>
    <version>5.6.75</version>
</dependency>

2、CosUtils类

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * @author ztl
 */
@Slf4j
public class CosUtils {

  private static COSClient sCosClient;

  private CosUtils() {
  }

  /**
   * 初始化CosClient实例,在Springboot初始化执行一次,可以保证COSClient实例只有一个
   */
  public static void initCosClient() {
    // 1 初始化
    String secretId = COSConfig.Tencent_secretId;
    String secretKey = COSConfig.Tencent_secretKey;
    COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
    // 2 设置 bucket
    Region region = new Region(COSConfig.Tencent_region);
    ClientConfig clientConfig = new ClientConfig(region);
    // 这里建议设置使用 https 协议
    clientConfig.setHttpProtocol(HttpProtocol.https);
    // 3 生成 cos 客户端。
    sCosClient = new COSClient(cred, clientConfig);
  }

  /**
   * COSClient实例获取
   *
   * @return cosclient
   */
  public static COSClient getCosClient() {
    initCosClient();
    return sCosClient;
  }

  /**
   * 上传文件
   *
   * @param file       MultipartFile类型的文件
   * @param bucketName 存储桶名称
   * @param key        文件路径及文件名称的组合
   *                   指定文件上传到 COS 上的路径
   * @return URL对象,在该对象中有很多方法,其中获取 url 链接的方法是:getContent()
   * @throws IOException
   */
  public static URL uploadFile
  (MultipartFile file, String bucketName, String key) throws IOException {
    // 指定要上传的文件,这里使用 流类型,不使用文件类型
    int inputStreamLength = file.getBytes().length;
    InputStream inputStream = file.getInputStream();
    // 数据流类型需要额外定义一个参数
    ObjectMetadata objectMetadata = new ObjectMetadata();
    // 上传的流如果能够获取准确的流长度,则推荐一定填写 content-length
    // 如果确实没办法获取到,则下面这行可以省略,但同时高级接口也没办法使用分块上传了
    objectMetadata.setContentLength(inputStreamLength);
    // 指定文件上传到 COS 上的路径,即对象键。例如对象键为folder/picture.jpg,则表示将文件 picture.jpg 上传到 folder 路径下
    // PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);
    PutObjectResult putObjectResult = sCosClient.putObject(putObjectRequest);
    System.out.println(putObjectResult.getRequestId());
    return getURL(bucketName, key);
  }


  public static String uploadFile(String fileName, InputStream inputStream) {
    URL url = uploadFile(fileName, inputStream, false);
    if (ObjectUtils.isEmpty(url) || StringUtils.isEmpty(url.getFile())) {
      return "";
    }
    return COSConfig.Tencent_domain + url.getFile();
  }

  public static URL uploadFile(String fileName, InputStream inputStream,
                               boolean shouldCloseStream) {

    log.info("cos uploadFile start;fileName:{}",fileName);
    // 数据流类型需要额外定义一个参数
    ObjectMetadata objectMetadata = new ObjectMetadata();
    // 上传的流如果能够获取准确的流长度,则推荐一定填写 content-length
    // 指定文件上传到 COS 上的路径,即对象键。
    // PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
    PutObjectRequest putObjectRequest = new PutObjectRequest(COSConfig.Tencent_bucketName, fileName, inputStream, objectMetadata);
    PutObjectResult putObjectResult = sCosClient.putObject(putObjectRequest);
    log.info("cos uploadFile putObjectResult requestId:{}",putObjectResult.getRequestId());
    if (shouldCloseStream) {
      try {
        inputStream.close();
      } catch (Exception e) {
        log.warn("error while closing stream", e);
      }
    }
    log.info("cos uploadFile end requestId:{},fileName:{}",putObjectResult.getRequestId(),fileName);
    return getURL(COSConfig.Tencent_bucketName, fileName);
  }

  /**
   * 重写方法,参入参数中没有bucketName,表示默认使用application.yml配置文件中的 bucketName
   *
   * @param file MultipartFile类型的文件
   * @param key  文件路径及文件名称的组合
   *             指定文件上传到 COS 上的路径,即对象键。例如对象键为folder/picture.jpg,则表示将文件 picture.jpg 上传到 folder 路径下
   * @return
   * @throws IOException
   */
  public static URL uploadFile(MultipartFile file, String key) throws IOException {
    return uploadFile(file, COSConfig.Tencent_bucketName, key);
  }

  /**
   * 根据 bucketName 和 key 获取 URL 对象
   *
   * @param bucketName 存储桶名称
   * @param key        文件路径及文件内容的组合
   * @return URL 对象
   */
  public static URL getURL(String bucketName, String key) {
    return sCosClient.getObjectUrl(bucketName, key);
  }

  /**
   * 重写方法,根据 key 获取 URL 对象
   *
   * @param key 文件路径及文件内容的组合
   * @return URL 对象
   */
  public static URL getURL(String key) {
    return getURL(COSConfig.Tencent_bucketName, key);
  }

  /**
   * 关闭 COSClient 实例,在 springboot 销毁时调用
   */
  public static void shutdownClient() {
    // 关闭客户端(关闭后台线程)
    sCosClient.shutdown();
  }
}

3、COSConfig类

import com.qcloud.cos.COSClient;
import lombok.Data;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = “prefix”, ignoreInvalidFields = true)
@RefreshScope
@Data
public class COSConfig implements InitializingBean, DisposableBean {
  private String bucketName;
  private String secretId;
  private String secretKey;
  private String region;
  private String domain;


  public static String Tencent_secretId;
  public static String Tencent_secretKey;
  public static String Tencent_bucketName;
  public static String Tencent_region;
  public static String Tencent_domain;

  @Override
  public void afterPropertiesSet() {
    Tencent_secretId = secretId;
    Tencent_secretKey = secretKey;
    Tencent_bucketName = bucketName;
    Tencent_region = region;
    Tencent_domain = domain;
  }

  @Override
  public void destroy() {
    CosUtils.shutdownClient();
  }

  @Bean
  public COSClient cosClient() {
    return CosUtils.getCosClient();
  }


}

4、具体使用:

String cosFileUrl = CosUtils.uploadFile(FILE_PATH+"/"+fileName, inputStream);
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值