admin管理员组

文章数量:1334969

简介:

对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。

网址:对象存储数据处理_COS数据处理_数据处理方案-腾讯云

大家可以选购这几种套餐

 选好套餐开通腾讯云存储对象Cos 开通以后的样子

主要分为俩大类请求方式一种是你自己封装http3请求从后端去发请求,另一种比较简单我这里推荐大家使用SDK的 。

导入pom.xml依赖

<dependency>
       <groupId>com.qcloud</groupId>
       <artifactId>cos_api</artifactId>
       <version>5.6.54</version>
</dependency>

编写config配置文件

public interface configuration {
    //id
    String secretId="*****";
    //key
    String secretKey="******";
    //创建桶对象时需要
    String APPID = "****";
    //创建桶时需要的区域
    String REGIONID = "***";// 区域
}

 封装工具包

1.(对存储桶操作)

package com.baidu.util;

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.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.Bucket;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.CreateBucketRequest;
import com.qcloud.cos.region.Region;

import java.util.List;

import static com.baidu.config.configuration.*;

/**
 * 使用cos对数据桶的基本操作
 * */
public class cosBucketUtil {
    /**
     * * 初始化CosClient相关配置, appid、accessKey、secretKey、region * @return
     */
    public static COSClient getCosClient() {
       // 1 初始化用户身份信息(secretId, secretKey)。
       // SECRETID和SECRETKEY请登录访问管理控制台 https://console.cloud.tencent/cam/capi 进行查看和管理
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); // 不传APPID也可以,APPID和ACCESSKE已经关联过
        // 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
       //REGIONID地域
        ClientConfig clientConfig = new ClientConfig(new Region(REGIONID));
        // 这里建议设置使用 https 协议
        // 从 5.6.54 版本开始,默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        //生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        return cosclient;
    }
    /***
     * 创建桶
     * cosClient 客户端连接对象
     * bucketName 自定义名称
     *
     * */
    public static Bucket createBucket(COSClient cosClient,String  bucketName) throws CosClientException, CosServiceException {
        String bucket = bucketName+"-"+APPID; //存储桶名称,格式:BucketName-APPID
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket);
// 设置 bucket 的权限为 Private(私有读写), 其他可选有公有读私有写, 公有读写
        createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        Bucket bucketResult = cosClient.createBucket(createBucketRequest);
        return bucketResult;
    };
    /**
     * 查询桶列表
     * cosClient 客户端连接对象
     * */
    public static List<Bucket> listBuckets(COSClient cosClient) throws CosClientException, CosServiceException{
        // 如果只调用 listBuckets 方法,则创建 cosClient 时指定 region 为 new Region("") 即可
        List<Bucket> buckets = cosClient.listBuckets();
        return buckets;
    }

    /**
     * 删除存储桶
     * 功能说明
     * 删除指定账号下的空存储桶。
     * cosClient 客户端连接对象,桶名称
     * **/
    public static void deleteBucket(COSClient cosClient,String bucketName) throws CosClientException, CosServiceException{
        cosClient.deleteBucket(bucketName);
    };

    /**
     * 判断某个桶是否存在
     * cosClient 初始化桶
     * bucketName 桶名称
     * */
    public static Boolean getdoesBucketExist(COSClient cosClient,String bucketName){
        return cosClient.doesBucketExist(bucketName+"-"+APPID);
    }

    public static void main(String[] args) {
     /*   //1.获取桶连接
        final COSClient cosClient = cosBucketUtil.getCosClient();
        String buckentName="ee";
        //2.判断桶是否存在
        final Boolean aBoolean = cosBucketUtil.getdoesBucketExist(cosClient, buckentName);
        if (aBoolean){
            //查询桶列表
             List<Bucket> buckets = cosBucketUtil.listBuckets(cosClient);
            for (Bucket bucket : buckets) {
                System.out.println("桶名称"+bucket.getName());
                System.out.println("桶的地域"+bucket.getLocation());
            }
        }else {
            //新增桶
             Bucket bucket = cosBucketUtil.createBucket(cosClient, buckentName);

        }*/
        final COSClient cosClient = cosBucketUtil.getCosClient();
//删除桶
        cosBucketUtil.deleteBucket(cosClient,"ee-1311510668");
    }
}

cos对上传的操作

package com.baidu.util;

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.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.UploadResult;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.*;

import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.baidu.config.configuration.*;

//上传操作
public class teanstreUtil {

    /**
     * * 初始化CosClient相关配置, appid、accessKey、secretKey、region * @return
     */
    public static COSClient getCosClient() {
        // 1 初始化用户身份信息(secretId, secretKey)。
        // SECRETID和SECRETKEY请登录访问管理控制台 https://console.cloud.tencent/cam/capi 进行查看和管理
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); // 不传APPID也可以,APPID和ACCESSKE已经关联过
        // 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        //REGIONID地域
        ClientConfig clientConfig = new ClientConfig(new Region(REGIONID));
        // 这里建议设置使用 https 协议
        // 从 5.6.54 版本开始,默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        //生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        return cosclient;
    }

    /** 创建 TransferManager 实例,这个实例用来后续调用高级接口
     * cosClient 初始化实例对象
     * **/
  public static   TransferManager createTransferManager(COSClient cosClient) {
        // 创建一个 COSClient 实例,这是访问 COS 服务的基础实例。
        // 详细代码参见本页: 简单操作 -> 创建 COSClient
        // 自定义线程池大小,建议在客户端与 COS 网络充足(例如使用腾讯云的 CVM,同地域上传 COS)的情况下,设置成16或32即可,可较充分的利用网络资源
        // 对于使用公网传输且网络带宽质量不高的情况,建议减小该值,避免因网速过慢,造成请求超时。
        ExecutorService threadPool = Executors.newFixedThreadPool(32);

        // 传入一个 threadpool, 若不传入线程池,默认 TransferManager 中会生成一个单线程的线程池。
        TransferManager transferManager = new TransferManager(cosClient, threadPool);

        // 设置高级接口的配置项
        // 分块上传阈值和分块大小分别为 5MB 和 1MB
        TransferManagerConfiguration transferManagerConfiguration = new TransferManagerConfiguration();
        transferManagerConfiguration.setMultipartUploadThreshold(5*1024*1024);
        transferManagerConfiguration.setMinimumUploadPartSize(1*1024*1024);
        transferManager.setConfiguration(transferManagerConfiguration);

        return transferManager;
    }
    /**
    *关闭 TransferManager
     * 在确定不再通过 TransferManager 的实例调用高级接口之后,一定要关闭这个实例,防止资源泄露。
    * ***/
    public static void shutdownTransferManager(TransferManager transferManager) {
        // 指定参数为 true, 则同时会关闭 transferManager 内部的 COSClient 实例。
        // 指定参数为 false, 则不会关闭 transferManager 内部的 COSClient 实例。
        transferManager.shutdownNow(Boolean.TRUE);
    }
    /**
     *
     * 文件上传
     *bucketName 桶名称 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
     * File 本地文件路径
     * key 对象键(Key)是对象在存储桶中的唯一标识。
     * */
    // 上传对象
    public static Upload upload(String bucketName,String key,String localFilePath) throws CosServiceException, CosClientException, InterruptedException {
        // 使用高级接口必须先保证本进程存在一个 TransferManager 实例,如果没有则创建
        final COSClient cosClient = teanstreUtil.getCosClient();
        // 详细代码参见本页:高级接口 -> 创建 TransferManager
        final TransferManager transferManager = teanstreUtil.createTransferManager(cosClient);
        File localFile = new File(localFilePath);
        //创建对象
        final PutObjectRequest putObjectRequest1 = new PutObjectRequest(bucketName, key, localFile);
        // 高级接口会返回一个异步结果Upload
            // 可同步地调用 waitForUploadResult 方法等待上传完成,成功返回UploadResult, 失败抛出异常
            Upload upload = transferManager.upload(putObjectRequest1);
            UploadResult uploadResult = upload.waitForUploadResult();
// 确定本进程不再使用 transferManager 实例之后,关闭之
// 详细代码参见本页:高级接口 -> 关闭 TransferManager
       teanstreUtil.shutdownTransferManager(transferManager);
        return upload;
    };
   /***
    * bucketName 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
    * String key上传的文件名称标识 唯一标识
    * 使用流的形式上传
    * */
    // 上传对象
    public static Upload uploads(String bucketName,String key,InputStream inputStream) throws CosServiceException, CosClientException{
        // 使用高级接口必须先保证本进程存在一个 TransferManager 实例,如果没有则创建
        final COSClient cosClient = teanstreUtil.getCosClient();
        // 详细代码参见本页:高级接口 -> 创建 TransferManager
        TransferManager transferManager = createTransferManager(cosClient);

        // 这里创建一个 ByteArrayInputStream 来作为示例,实际中这里应该是您要上传的 InputStream 类型的流


        ObjectMetadata objectMetadata = new ObjectMetadata();
// 上传的流如果能够获取准确的流长度,则推荐一定填写 content-length
// 如果确实没办法获取到,则下面这行可以省略,但同时高级接口也没办法使用分块上传了
    /*    objectMetadata.setContentLength(inputStreamLength);*/

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);
        Upload upload=null;
        try {
            // 高级接口会返回一个异步结果Upload
            // 可同步地调用 waitForUploadResult 方法等待上传完成,成功返回UploadResult, 失败抛出异常
             upload = transferManager.upload(putObjectRequest);
            UploadResult uploadResult = upload.waitForUploadResult();
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        teanstreUtil.shutdownTransferManager(transferManager);

        return upload;
    };
//上传本地目录
    /**
     * bucketName // 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
     *virtualDirectoryKeyPrefix // 设置文件上传到 bucket 之后的前缀目录,设置为 “”,表示上传到 bucket 的根目录
     * directory 本地路径 // 要上传的文件夹的绝对路径
     * includeSubdirectories // 是否递归上传目录下的子目录,如果是 true,子目录下的文件也会上传,且cos上会保持目录结构
     * */
//TransferManager 实例封装了从本地一个目录来读取文件并且上传到 COS 的功能,这个功能可以在不破坏目录结构的情况下,将文件上传。同时,也可以指定将目录下的文件上传到另一个目录。
public static MultipleFileUpload uploadDirectory(String bucketName, String virtualDirectoryKeyPrefix,
                                          File directory, boolean includeSubdirectories){
    final COSClient cosClient = teanstreUtil.getCosClient();
    TransferManager transferManager = createTransferManager(cosClient);

    MultipleFileUpload upload=null;
    try {
        // 返回一个异步结果Upload, 可同步的调用waitForUploadResult等待upload结束, 成功返回UploadResult, 失败抛出异常.
         upload = transferManager.uploadDirectory(bucketName, virtualDirectoryKeyPrefix, directory, includeSubdirectories);
        // 或者阻塞等待完成
        upload.waitForCompletion();
    } catch (CosServiceException e) {
        e.printStackTrace();
    } catch (CosClientException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    teanstreUtil.shutdownTransferManager(transferManager);
    return upload;
};


    public static void main(String[] args) throws InterruptedException, FileNotFoundException {

teanstreUtil.uploadDirectory("ems-1311510668","preif",new File("D:\\text"),Boolean.TRUE);
    }


}

 cos下载对象操作

package com.baidu.util;

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.demo.BucketRefererDemo;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.Download;
import com.qcloud.cos.transfer.MultipleFileDownload;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.utils.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.baidu.config.configuration.secretId;
import static com.baidu.config.configuration.*;
import static com.qcloud.cos.demo.BucketRefererDemo.cosClient;

public class cosDowbloadUtil {
    // 创建 COSClient 实例,这个实例用来后续调用请求
public static COSClient createCOSClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

        // ClientConfig 中包含了后续请求 COS 的客户端设置:
        ClientConfig clientConfig = new ClientConfig();

        // 设置 bucket 的地域
        // COS_REGION 请参照 https://cloud.tencent/document/product/436/6224
        clientConfig.setRegion(new Region("ap-beijing"));

        // 设置请求协议, http 或者 https
        // 5.6.53 及更低的版本,建议设置使用 https 协议
        // 5.6.54 及更高版本,默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);

        // 以下的设置,是可选的:

        // 设置 socket 读取超时,默认 30s
        clientConfig.setSocketTimeout(30*1000);
        // 设置建立连接超时,默认 30s
        clientConfig.setConnectionTimeout(30*1000);

        // 如果需要的话,设置 http 代理,ip 以及 port
      /*  clientConfig.setHttpProxyIp("httpProxyIp");
        clientConfig.setHttpProxyPort(80);*/
        // 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }

    // 创建 TransferManager 实例,这个实例用来后续调用高级接口
public static TransferManager createTransferManager(){
      // 创建一个 COSClient 实例,这是访问 COS 服务的基础实例。
      // 详细代码参见本页: 简单操作 -> 创建 COSClient
     COSClient cosClient = cosDowbloadUtil.createCOSClient();
    // 自定义线程池大小,建议在客户端与 COS 网络充足(例如使用腾讯云的 CVM,同地域上传 COS)的情况下,设置成16或32即可,可较充分的利用网络资源
      // 对于使用公网传输且网络带宽质量不高的情况,建议减小该值,避免因网速过慢,造成请求超时。
      ExecutorService threadPool = Executors.newFixedThreadPool(32);
      // 传入一个 threadpool, 若不传入线程池,默认 TransferManager 中会生成一个单线程的线程池。
      TransferManager transferManager = new TransferManager(cosClient, threadPool);
      return transferManager;
  }

/*    // 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
    String bucketName = "examplebucket-1250000000";
    // 对象键(Key)是对象在存储桶中的唯一标识。详情请参见 [对象键](https://cloud.tencent/document/product/436/13324)
    String key = "exampleobject";*/
    public static Download download(String bucketName,String key,  String localFilePath){
        // 使用高级接口必须先保证本进程存在一个 TransferManager 实例,如果没有则创建
// 详细代码参见本页:高级接口 -> 创建 TransferManager
        final TransferManager transferManager = cosDowbloadUtil.createTransferManager();
        //本地存储路径
        File downloadFile = new File(localFilePath);
        Download download=null;
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        try {
            // 返回一个异步结果 Donload, 可同步的调用 waitForCompletion 等待下载结束, 成功返回 void, 失败抛出异常
             download = transferManager.download(getObjectRequest, downloadFile);
            download.waitForCompletion();
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

// 确定本进程不再使用 transferManager 实例之后,关闭之
// 详细代码参见本页:高级接口 -> 关闭 TransferManager
        cosDowbloadUtil.shutdownTransferManager(transferManager);
        return download;
    };

   public static void shutdownTransferManager(TransferManager transferManager) {
        // 指定参数为 true, 则同时会关闭 transferManager 内部的 COSClient 实例。
        // 指定参数为 false, 则不会关闭 transferManager 内部的 COSClient 实例。
        transferManager.shutdownNow(true);
    }
    /**
     * 断点下载对象利用了分 range 多线程同时下载的方式下载对象,并在完成之后做完整性校验。如果下载过程中出现异常中断,重新下载时不会下载已经下载过的 range (源文件如果在重启前被修改,则会从头下载)。
     * 适合大文件下载。
     * */
    public static Download downloads(String bucketName,String key,String localFilePath,
                             boolean resumableDownload){
                            // 使用高级接口必须先保证本进程存在一个 TransferManager 实例,如果没有则创建
                            // 详细代码参见本页:高级接口 -> 创建 TransferManager
         TransferManager transferManager = cosDowbloadUtil.createTransferManager();
        File downloadFile = new File(localFilePath);
        Download download=null;
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        try {
            // 返回一个异步结果 Donload, 可同步的调用 waitForCompletion 等待下载结束, 成功返回 void, 失败抛出异常
             download = transferManager.download(getObjectRequest, downloadFile, resumableDownload);
            download.waitForCompletion();
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        cosDowbloadUtil.shutdownTransferManager(transferManager);
        return download;
    };
    /**
     * 下载到目录
     * // 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
     *  @String bucketName = "examplebucket-1250000000";
     *         // 设置要下载的对象的前缀(相当于cos上的一个目录),如果设置成 "",则下载整个 bucket。
     *         String cos_path = "/prefix";
     *         // 要保存下载的文件的文件夹的绝对路径
     *         String dir_path = "/to/mydir";
     * */
    public static MultipleFileDownload downloadDirectory(String bucketName, String cos_path,String dir_path
                                                  ) {
// 使用高级接口必须先保证本进程存在一个 TransferManager 实例,如果没有则创建
// 详细代码参见本页:高级接口 -> 示例代码:创建 TransferManager
         TransferManager transferManager = cosDowbloadUtil.createTransferManager();
        MultipleFileDownload download=null;
        try {
            // 返回一个异步结果download, 可同步的调用waitForUploadResult等待download结束.
             download = transferManager.downloadDirectory(bucketName, cos_path, new File(dir_path));
            // 或者阻塞等待完成
            download.waitForCompletion();

            System.out.println("download directory done.");
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

// 确定本进程不再使用 transferManager 实例之后,关闭之
// 详细代码参见本页:高级接口 -> 示例代码:关闭 TransferManager
        cosDowbloadUtil.shutdownTransferManager(transferManager);
        return download;
    }


    public static void main(String[] args) {
        //cosDowbloadUtil.download("ems-1311510668","rizhi.png","D:\\360"+"\\"+"rizhi.png");
cosDowbloadUtil.downloadDirectory("ems-1311510668","/preif","D:\\360");
    }
    public static Boolean shangchuan(MultipartFile multipartFile){
       // multipartFile.transferTo(new File(realPath,aa.getOriginalFilename()));//文件上传
       return Boolean.TRUE;
    }

}

 列出cos对象

package com.baidu.util;

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.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.ListObjectsRequest;
import com.qcloud.cos.model.ObjectListing;
import com.qcloud.cos.region.Region;

import java.util.List;

import static com.baidu.config.configuration.*;
/**
 * 列出当前对象**/
public class cosLikeUtil {
    // 创建 COSClient 实例,这个实例用来后续调用请求
  public static   COSClient createCOSClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

        // ClientConfig 中包含了后续请求 COS 的客户端设置:
        ClientConfig clientConfig = new ClientConfig();

        // 设置 bucket 的地域
        // COS_REGION 请参照 https://cloud.tencent/document/product/436/6224
        clientConfig.setRegion(new Region(REGIONID));

        // 设置请求协议, http 或者 https
        // 5.6.53 及更低的版本,建议设置使用 https 协议
        // 5.6.54 及更高版本,默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);

        // 以下的设置,是可选的:

        // 设置 socket 读取超时,默认 30s
        clientConfig.setSocketTimeout(30*1000);
        // 设置建立连接超时,默认 30s
        clientConfig.setConnectionTimeout(30*1000);

   /*     // 如果需要的话,设置 http 代理,ip 以及 port
        clientConfig.setHttpProxyIp("httpProxyIp");
        clientConfig.setHttpProxyPort(80);*/

        // 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }

   /** // 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
    String bucketName = "examplebucket-1250000000";
    如果没有就穿空字符串 ""
    **/

    public static ObjectListing listObjects(String bucketName,String prefix) throws CosClientException, CosServiceException{
        // 调用 COS 接口之前必须保证本进程存在一个 COSClient 实例,如果没有则创建
// 详细代码参见本页:简单操作 -> 创建 COSClient
         COSClient cosClient = cosLikeUtil.createCOSClient();

        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
// 设置 bucket 名称
        listObjectsRequest.setBucketName(bucketName);
// 设置列出的对象名以 prefix 为前缀
        listObjectsRequest.setPrefix(prefix);
// 设置最大列出多少个对象, 一次 listobject 最大支持1000
        listObjectsRequest.setMaxKeys(1000);

// 保存列出的结果
        ObjectListing objectListing = null;

        try {
            objectListing = cosClient.listObjects(listObjectsRequest);
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
// 确认本进程不再使用 cosClient 实例之后,关闭之
        cosClient.shutdown();
        return objectListing;
    };

    public static void main(String[] args) {
        final ObjectListing objectListing = cosLikeUtil.listObjects("ems-1311510668", "");
        objectListing.getObjectSummaries().forEach(cosObjectSummary -> {
            // 对象的 key
            String key = cosObjectSummary.getKey();
            // 对象的etag
            String etag = cosObjectSummary.getETag();
            // 对象的长度
            long fileSize = cosObjectSummary.getSize();
            // 对象的存储类型
            String storageClasses = cosObjectSummary.getStorageClass();
            System.out.println(key);
            System.out.println(etag);
            System.out.println(fileSize);
            System.out.println(storageClasses);
        });

        if (objectListing.isTruncated()) {
            // 表示还没有列完,被截断了

            // 下一次开始的位置
            String nextMarker = objectListing.getNextMarker();
        }

    }
}

删除对象



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.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.exception.MultiObjectDeleteException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;

import java.util.ArrayList;
import java.util.List;

import static com.baidu.config.configuration.*;

public class cosDelectUtil {
    //创建 COSClient
    // 创建 COSClient 实例,这个实例用来后续调用请求
public static COSClient createCOSClient() {
        // 设置用户身份信息。
        // SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent/cam/capi 进行查看和管理
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // ClientConfig 中包含了后续请求 COS 的客户端设置:
        ClientConfig clientConfig = new ClientConfig();
        // 设置 bucket 的地域
        // COS_REGION 请参照 https://cloud.tencent/document/product/436/6224
        clientConfig.setRegion(new Region(REGIONID));
        // 设置请求协议, http 或者 https
        // 5.6.53 及更低的版本,建议设置使用 https 协议
        // 5.6.54 及更高版本,默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 以下的设置,是可选的:
        // 设置 socket 读取超时,默认 30s
        clientConfig.setSocketTimeout(30*1000);
        // 设置建立连接超时,默认 30s
        clientConfig.setConnectionTimeout(30*1000);
        // 如果需要的话,设置 http 代理,ip 以及 port
  /*      clientConfig.setHttpProxyIp("httpProxyIp");
        clientConfig.setHttpProxyPort(80);*/
        // 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }
 //删除对象
    /***
     * @param bucketName 桶名称
     * @param key 文件名称
     * */
public static void deleteObject(String bucketName, String key) throws CosClientException, CosServiceException{
     // 调用 COS 接口之前必须保证本进程存在一个 COSClient 实例,如果没有则创建
// 详细代码参见本页:简单操作 -> 创建 COSClient
     COSClient cosClient = cosDelectUtil.createCOSClient();
// 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
     String bucketNames = bucketName+"-"+APPID;
// 对象键(Key)是对象在存储桶中的唯一标识。详情请参见 [对象键](https://cloud.tencent/document/product/436/13324)
     try {
         cosClient.deleteObject(bucketNames, key);
     } catch (CosServiceException e) {
         e.printStackTrace();
     } catch (CosClientException e) {
         e.printStackTrace();
     }

// 确认本进程不再使用 cosClient 实例之后,关闭之
     cosClient.shutdown();
 }
//批量删除对象
public static DeleteObjectsResult deleteObjects(String bucketName,ArrayList<DeleteObjectsRequest.KeyVersion> list) throws MultiObjectDeleteException, CosClientException, CosServiceException{
    // 调用 COS 接口之前必须保证本进程存在一个 COSClient 实例,如果没有则创建
// 详细代码参见本页:简单操作 -> 创建 COSClient
    COSClient cosClient = cosDelectUtil.createCOSClient();

// 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
    String bucketNames = bucketName+"-"+APPID;

    DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketNames);
    deleteObjectsRequest.setKeys(list);
    DeleteObjectsResult deleteObjectsResult=null;
    try {
         deleteObjectsResult = cosClient.deleteObjects(deleteObjectsRequest);
        List<DeleteObjectsResult.DeletedObject> deleteObjectResultArray = deleteObjectsResult.getDeletedObjects();
    } catch (MultiObjectDeleteException mde) {
        // 如果部分删除成功部分失败, 返回 MultiObjectDeleteException
        List<DeleteObjectsResult.DeletedObject> deleteObjects = mde.getDeletedObjects();
        List<MultiObjectDeleteException.DeleteError> deleteErrors = mde.getErrors();
    } catch (CosServiceException e) {
        e.printStackTrace();
    } catch (CosClientException e) {
        e.printStackTrace();
    }
    // 确认本进程不再使用 cosClient 实例之后,关闭之
    cosClient.shutdown();
return  deleteObjectsResult;
}
//删除目录
    /***
     * @param bucketName 桶名称
     * @param delDir 目录名称
     * */
public static void delemkidr(String bucketName,String delDir){
// 列目录实现参考:列出对象 -> 简单操作 -> 列出目录下的对象和子目录
// 批量删除实现参考本页:批量删除对象
    final StringBuilder stringBuilder = new StringBuilder();
          stringBuilder.append(bucketName);
          stringBuilder.append("-");
          stringBuilder.append(APPID);
// 调用 COS 接口之前必须保证本进程存在一个 COSClient 实例,如果没有则创建
// 详细代码参见本页:简单操作 -> 创建 COSClient
    COSClient cosClient = cosDelectUtil.createCOSClient();
    ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
// 设置 bucket 名称
    listObjectsRequest.setBucketName(stringBuilder.toString());
// prefix 表示列出的对象名以 prefix 为前缀
// 这里填要列出的目录的相对 bucket 的路径
    listObjectsRequest.setPrefix(delDir);
// 设置最大遍历出多少个对象, 一次 listobject 最大支持1000
    listObjectsRequest.setMaxKeys(1000);
// 保存每次列出的结果
    ObjectListing objectListing = null;
    do {
        try {
            objectListing = cosClient.listObjects(listObjectsRequest);
        } catch (CosServiceException e) {
            e.printStackTrace();
            return;
        } catch (CosClientException e) {
            e.printStackTrace();
            return;
        }

        // 这里保存列出的对象列表
        List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();

        ArrayList<DeleteObjectsRequest.KeyVersion> delObjects = new ArrayList<DeleteObjectsRequest.KeyVersion>();

        for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
            delObjects.add(new DeleteObjectsRequest.KeyVersion(cosObjectSummary.getKey()));
        }

        DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName);

        deleteObjectsRequest.setKeys(delObjects);

        try {
            DeleteObjectsResult deleteObjectsResult = cosClient.deleteObjects(deleteObjectsRequest);
            List<DeleteObjectsResult.DeletedObject> deleteObjectResultArray = deleteObjectsResult.getDeletedObjects();
        } catch (MultiObjectDeleteException mde) {
            // 如果部分删除成功部分失败, 返回 MultiObjectDeleteException
            List<DeleteObjectsResult.DeletedObject> deleteObjects = mde.getDeletedObjects();
            List<MultiObjectDeleteException.DeleteError> deleteErrors = mde.getErrors();
        } catch (CosServiceException e) {
            e.printStackTrace();
            return;
        } catch (CosClientException e) {
            e.printStackTrace();
            return;
        }

        // 标记下一次开始的位置
        String nextMarker = objectListing.getNextMarker();
        listObjectsRequest.setMarker(nextMarker);
    } while (objectListing.isTruncated());
    }
    public static void main(String[] args) {
    cosDelectUtil.delemkidr("ems","preif");

    }
}

本文标签: 腾讯cos