全部产品
Search
文档中心

对象存储 OSS:Java设置对象标签

更新时间:Oct 24, 2024

OSS支持使用对象标签(Object Tagging)对存储空间(Bucket)中的文件(Object)进行分类,您可以针对相同标签的Object设置生命周期规则、访问权限等。

注意事项

  • 在配置对象标签之前,请确保您已了解该功能。详情请参见对象标签

  • 本文以华东1(杭州)外网Endpoint为例。如果您希望通过与OSS同地域的其他阿里云产品访问OSS,请使用内网Endpoint。关于OSS支持的Region与Endpoint的对应关系,请参见OSS访问域名、数据中心、开放端口

  • 本文以从环境变量读取访问凭证为例。如何配置访问凭证,请参见Java配置访问凭证

  • 本文以OSS域名新建OSSClient为例。如果您希望通过自定义域名、STS等方式新建OSSClient,请参见新建OSSClient

  • 仅Java SDK 3.5.0及以上版本支持设置对象标签。

  • 要设置对象标签,您必须具有oss:PutObjectTagging权限。具体操作,请参见为RAM用户授权自定义的权限策略

上传Object时添加对象标签

以下分别介绍简单上传、分片上传、追加上传以及断点续传上传场景下为上传的Object添加对象标签的示例。

  • 简单上传时添加对象标签

    以下代码用于简单上传时添加对象标签。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    import java.io.ByteArrayInputStream;
    import java.util.HashMap;
    import java.util.Map;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "examplebucket";
            // 填写Object完整路径,Object完整路径中不能包含Bucket名称。例如exampledir/exampleobject.txt。
            String objectName = "exampledir/exampleobject.txt";
            // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 创建OSSClient实例。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                Map<String, String> tags = new HashMap<String, String>();
                // 依次填写对象标签的键(例如owner)和值(例如John)。
                tags.put("owner", "John");
                tags.put("type", "document");
    
                // 在HTTP header中设置标签信息。
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setObjectTagging(tags);
    
                // 上传文件的同时设置标签信息。
                String content = "<yourtContent>";
                ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()), metadata);
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • 分片上传时添加对象标签

    以下代码用于分片上传时添加对象标签。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    import java.io.*;
    import java.util.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "examplebucket";
            // 填写Object完整路径,Object完整路径中不能包含Bucket名称。例如exampledir/exampleobject.txt。
            String objectName = "exampledir/exampleobject.txt";
            // 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
            String localFile = "D:\\localpath\\examplefile.txt";
            // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 创建OSSClient实例。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                /*
                   步骤1:初始化一个分片上传事件。
                */
                // 在HTTP header中设置标签信息。
                Map<String, String> tags = new HashMap<String, String>();
                // 依次填写对象标签的键(例如owner)和值(例如John)。
                tags.put("owner", "John");
                tags.put("type", "document");
    
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setObjectTagging(tags);
    
                // 发起InitiateMultipartUploadRequest请求的同时设置标签信息。
                InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName, metadata);
                InitiateMultipartUploadResult result = ossClient.initiateMultipartUpload(request);
                // 返回uploadId,它是分片上传事件的唯一标识。您可以根据该ID来发起相关的操作,例如取消分片上传、查询分片上传等。
                String uploadId = result.getUploadId();
    
                /*
                   步骤2:上传分片。
                */
                // partETags是PartETag的集合。PartETag由分片的ETag和分片号组成。
                List<PartETag> partETags =  new ArrayList<PartETag>();
                // 计算文件有多少个分片。
                final long partSize = 1 * 1024 * 1024L;   // 1 MB。
                final File sampleFile = new File(localFile);
                long fileLength = sampleFile.length();
                int partCount = (int) (fileLength / partSize);
                if (fileLength % partSize != 0) {
                    partCount++;
                }
                // 遍历分片上传。
                for (int i = 0; i < partCount; i++) {
                    long startPos = i * partSize;
                    long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
                    InputStream instream = null;
                    try {
                        instream = new FileInputStream(sampleFile);
                        // 跳过已上传的分片。
                        instream.skip(startPos);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    UploadPartRequest uploadPartRequest = new UploadPartRequest();
                    uploadPartRequest.setBucketName(bucketName);
                    uploadPartRequest.setKey(objectName);
                    uploadPartRequest.setUploadId(uploadId);
                    uploadPartRequest.setInputStream(instream);
                    // 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100 KB。
                    uploadPartRequest.setPartSize(curPartSize);
                    // 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出该范围,OSS将返回InvalidArgument的错误码。
                    uploadPartRequest.setPartNumber( i + 1);
                    // 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。
                    UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
                    // 每次上传分片之后,OSS的返回结果会包含一个PartETag。PartETag将被保存到partETags中。
                    partETags.add(uploadPartResult.getPartETag());
                }
    
                /* 步骤3:完成分片上传。
                 */
                // partETags必须按分片号升序排列。
                Collections.sort(partETags, new Comparator<PartETag>() {
                    public int compare(PartETag p1, PartETag p2) {
                        return p1.getPartNumber() - p2.getPartNumber();
                    }
                });
                // 在执行该操作时,需要提供所有有效的partETags。OSS收到提交的partETags后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。
                CompleteMultipartUploadRequest completeMultipartUploadRequest =
                        new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);
                ossClient.completeMultipartUpload(completeMultipartUploadRequest);
    
                // 查看文件标签信息。
                TagSet tagSet = ossClient.getObjectTagging(bucketName, objectName);
                Map<String, String> getTags = tagSet.getAllTags();
                System.out.println("object tagging: "+ getTags.toString());
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • 追加上传时添加对象标签

    以下代码用于追加上传时添加对象标签。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    import java.io.*;
    import java.util.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "examplebucket";
            // 填写Object完整路径,Object完整路径中不能包含Bucket名称。例如exampledir/exampleobject.txt。
            String objectName = "exampledir/exampleobject.txt";
            // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 创建OSSClient实例。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                String content1 = "Hello OSS A \n";
                String content2 = "Hello OSS B \n";
                String content3 = "Hello OSS C \n";
    
                Map<String, String> tags = new HashMap<String, String>();
                // 依次填写对象标签的键(例如owner)和值(例如John)。
                tags.put("owner", "John");
                tags.put("type", "document");
    
                ObjectMetadata meta = new ObjectMetadata();
                // 设置上传文件的标签。
                meta.setObjectTagging(tags);
                // 指定上传的内容类型。
                meta.setContentType("text/plain");
    
                // 通过AppendObjectRequest设置多个参数。
                AppendObjectRequest appendObjectRequest = new AppendObjectRequest(bucketName, objectName, new ByteArrayInputStream(content1.getBytes()), meta);
    
                // 通过AppendObjectRequest设置单个参数。
                //appendObjectRequest.setBucketName(bucketName);
                //appendObjectRequest.setKey(objectName);
                // 设置待追加的内容。可选类型包括InputStream类型和File类型两种。此处为InputStream类型。
                //appendObjectRequest.setInputStream(new ByteArrayInputStream(content1.getBytes()));
                // 设置待追加的内容。可选类型包括InputStream类型和File类型两种。此处为File类型。
                // 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
                //appendObjectRequest.setFile(new File("D:\\localpath\\examplefile.txt"));
                // 指定文件的元数据,第一次追加时有效。
                //appendObjectRequest.setMetadata(meta);
    
                // 第一次追加。只有第一次追加上传时设置的标签生效。
                // 设置文件的追加位置。
                appendObjectRequest.setPosition(0L);
                AppendObjectResult appendObjectResult = ossClient.appendObject(appendObjectRequest);
                // 文件的64位CRC值。此值根据ECMA-182标准计算得出。
                System.out.println(appendObjectResult.getObjectCRC());
    
                // 第二次追加。
                // nextPosition表示下一次请求中应当提供的Position,即文件当前的长度。
                appendObjectRequest.setPosition(appendObjectResult.getNextPosition());
                appendObjectRequest.setInputStream(new ByteArrayInputStream(content2.getBytes()));
                appendObjectResult = ossClient.appendObject(appendObjectRequest);
    
                // 第三次追加。
                appendObjectRequest.setPosition(appendObjectResult.getNextPosition());
                appendObjectRequest.setInputStream(new ByteArrayInputStream(content3.getBytes()));
                appendObjectResult = ossClient.appendObject(appendObjectRequest);
    
                // 查看上传文件的标签信息。
                TagSet tagSet = ossClient.getObjectTagging(bucketName, objectName);
                Map<String, String> getTags = tagSet.getAllTags();
                System.out.println("object tagging: "+ getTags.toString());
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • 断点续传上传时添加对象标签

    以下代码用于断点续传上传时添加对象标签。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    import java.util.*;
    
    public class Demo {
        public static void main(String[] args) throws Throwable {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "examplebucket";
            // 填写Object完整路径,Object完整路径中不能包含Bucket名称。例如exampledir/exampleobject.txt。
            String objectName = "exampledir/exampleobject.txt";
            // 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
            String localFile = "D:\\localpath\\examplefile.txt";
            // 记录本地分片上传结果的文件。本地分片上传结果的文件要求以.ucp为后缀,且与通过localFile指定的本地文件在同一路径下。
            // 上传完成后,该文件会被删除。
            String yourCheckpointFile = "D:\\localpath\\uploadfile.ucp";
            // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 创建OSSClient实例。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // 设置文件的标签信息。
                Map<String, String> tags = new HashMap<String, String>();
                // 依次填写对象标签的键(例如owner)和值(例如John)。
                tags.put("owner", "John");
                tags.put("type", "document");
    
                ObjectMetadata meta = new ObjectMetadata();
                // 指定上传的内容类型。
                meta.setContentType("text/plain");
                // 设置文件标签。
                meta.setObjectTagging(tags);
    
                // 通过UploadFileRequest设置多个参数。
                UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName,objectName);
    
                // 通过UploadFileRequest设置单个参数。
                // 指定Bucket名称。
                //uploadFileRequest.setBucketName(bucketName);
                // 指定Object完整路径。Object完整路径中不能包含Bucket名称。
                //uploadFileRequest.setKey(objectName);
                // 指定待上传的本地文件。
                uploadFileRequest.setUploadFile(localFile);
                // 指定上传并发线程数,默认值为1。
                uploadFileRequest.setTaskNum(5);
                // 指定上传的分片大小,取值范围为100 KB~5 GB,默认上传的分片大小是整个文件大小的1/10000。
                uploadFileRequest.setPartSize(1 * 1024 * 1024);
                // 开启断点续传,默认为关闭。
                uploadFileRequest.setEnableCheckpoint(true);
                // 记录本地分片上传结果的文件。开启断点续传功能时需要设置此参数,上传过程中的进度信息会保存在该文件中,如果某一分片上传失败,再次上传时会根据文件中记录的点继续上传。上传完成后,该文件会被删除。默认与待上传的本地文件同目录,为uploadFile.ucp。
                uploadFileRequest.setCheckpointFile(yourCheckpointFile);
                // 文件的元数据。
                uploadFileRequest.setObjectMetadata(meta);
                // 设置上传成功回调,参数为Callback类型。
                //uploadFileRequest.setCallback("yourCallbackEvent");
    
                // 断点续传上传, 同时设置文件标签。
                ossClient.uploadFile(uploadFileRequest);
    
                // 查看文件的标签信息。
                TagSet tagSet = ossClient.getObjectTagging(bucketName, objectName);
                Map<String, String> getTags = tagSet.getAllTags();
                System.out.println("object tagging: "+ getTags.toString());
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }

为已上传Object添加或更改对象标签

如果上传Object时未添加对象标签或者添加的对象标签不满足使用需求,您可以在上传Object后为Object添加或更改对象标签。

以下代码用于为已上传Object添加或更改对象标签。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.util.*;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";
        // 填写Object完整路径,Object完整路径中不能包含Bucket名称。例如exampledir/exampleobject.txt。
        String objectName = "exampledir/exampleobject.txt";
        // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
        String region = "cn-hangzhou";

        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            Map<String, String> tags = new HashMap<String, String>();
            // 依次填写对象标签的键(例如owner)和值(例如John)。
            tags.put("owner", "John");
            tags.put("type", "document");

            // 为文件设置标签。
            ossClient.setObjectTagging(bucketName, objectName, tags);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

为Object指定版本添加或更改对象标签

在已开启版本控制的Bucket中,通过指定Object的版本ID(versionId),您可以为Object指定版本添加或更改对象标签。

以下代码用于为Object指定版本添加或更改对象标签。

说明

关于获取versionId的具体操作,请参见列举文件

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.SetObjectTaggingRequest;
import java.util.*;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";
        // 填写Object完整路径,Object完整路径中不能包含Bucket名称。例如exampledir/exampleobject.txt。
        String objectName = "exampledir/exampleobject.txt";
        // 填写Object的版本ID,例如CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****。
        String versionId = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****";
        // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
        String region = "cn-hangzhou";

        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            Map<String, String> tags = new HashMap<String, String>(1);
            // 依次填写对象标签的键(例如owner)和值(例如John)。
            tags.put("owner", "John");
            tags.put("type", "document");

            SetObjectTaggingRequest setObjectTaggingRequest = new SetObjectTaggingRequest(bucketName, objectName, tags);
            setObjectTaggingRequest.setVersionId(versionId);
            ossClient.setObjectTagging(setObjectTaggingRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

拷贝Object时设置对象标签

拷贝Object时,可以指定如何设置目标Object的对象标签。取值如下:

  • Copy(默认值):复制源Object的对象标签到目标Object。

  • Replace:忽略源Object的对象标签,直接采用请求中指定的对象标签。

以下分别提供了简单拷贝1 GB以下的Object及分片拷贝1 GB以上的Object时设置对象标签的详细示例。

  • 简单拷贝时设置对象标签

    以下代码用于简单拷贝1 GB以下的Object时设置对象标签。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.internal.OSSHeaders;
    import com.aliyun.oss.model.CopyObjectRequest;
    import com.aliyun.oss.model.CopyObjectResult;
    import com.aliyun.oss.model.TagSet;
    import java.util.*;
    
    public class Demo {
        public static void main(String[] args) throws Throwable {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填写源Bucket名称,例如srcexamplebucket。
            String sourceBucketName = "srcexamplebucket";
            // 填写源Object完整路径,Object完整路径中不能包含Bucket名称。例如srcexampledir/exampleobject.txt。
            String sourceObjectName = "srcexampledir/exampleobject.txt";
            // 填写目标Bucket名称,例如destexamplebucket。
            String destinationBucketName = "destexamplebucket";
            // 填写目标Object完整路径,Object完整路径中不能包含Bucket名称。例如destexampledir/exampleobject.txt。
            String destinationObjectName = "destexampledir/exampleobject.txt";
            // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 创建OSSClient实例。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // 创建CopyObjectRequest对象。
                CopyObjectRequest copyObjectRequest = new CopyObjectRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName);
    
                // 设置目标文件的标签。如果不设置headers,目标文件默认复制源文件的标签。
                Map<String, String> headers = new HashMap<String, String>();
                headers.put(OSSHeaders.COPY_OBJECT_TAGGING_DIRECTIVE, "REPLACE");
                headers.put(OSSHeaders.OSS_TAGGING, "key1=value1&key2=value2");
                copyObjectRequest.setHeaders(headers);
    
                // 复制文件。
                CopyObjectResult result = ossClient.copyObject(copyObjectRequest);
                System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());
    
                // 查看目标文件的标签信息。
                TagSet tagSet = ossClient.getObjectTagging(destinationBucketName, destinationObjectName);
                Map<String, String> getTags = tagSet.getAllTags();
                System.out.println("dest object tagging: "+ getTags.toString());
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
                        
  • 分片拷贝时设置对象标签

    以下代码用于分片拷贝1 GB以上的Object时设置对象标签。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    import java.util.*;
    
    public class Demo {
        public static void main(String[] args) throws Throwable {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填写源Bucket名称,例如srcexamplebucket。
            String sourceBucketName = "srcexamplebucket";
            // 填写源Object完整路径,Object完整路径中不能包含Bucket名称。例如srcexampledir/exampleobject.txt。
            String sourceObjectName = "srcexampledir/exampleobject.txt";
            // 填写目标Bucket名称,例如destexamplebucket。
            String destinationBucketName = "destexamplebucket";
            // 填写目标Object完整路径,Object完整路径中不能包含Bucket名称。例如destexampledir/exampleobject.txt。
            String destinationObjectName = "destexampledir/exampleobject.txt";
            // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 创建OSSClient实例。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                ObjectMetadata objectMetadata = ossClient.getObjectMetadata(sourceBucketName, sourceObjectName);
                // 获取被拷贝文件的大小。
                long contentLength = objectMetadata.getContentLength();
                // 设置分片大小为10 MB。
                long partSize = 1024 * 1024 * 10;
                // 计算分片总数。
                int partCount = (int) (contentLength / partSize);
                if (contentLength % partSize != 0) {
                    partCount++;
                }
    
                System.out.println("total part count:" + partCount);
    
                // 在HTTP header中设置标签信息。
                Map<String, String> tags2 = new HashMap<String, String>();
                // 依次填写对象标签的键(owner)和值(例如Lily)。
                tags2.put("owner", "Lily");
                tags2.put("type", "document");
    
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setObjectTagging(tags2);
    
                // 初始化拷贝任务。同时给要拷贝的目标文件设置标签。
                InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(destinationBucketName, destinationObjectName, metadata);
                InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient.initiateMultipartUpload(initiateMultipartUploadRequest);
                String uploadId = initiateMultipartUploadResult.getUploadId();
    
                // 分片拷贝。
                List<PartETag> partETags = new ArrayList<PartETag>();
                for (int i = 0; i < partCount; i++) {
                    // 计算每个分片的大小。
                    long skipBytes = partSize * i;
                    long size = partSize < contentLength - skipBytes ? partSize : contentLength - skipBytes;
    
                    // 创建UploadPartCopyRequest。可以通过UploadPartCopyRequest指定限定条件。
                    UploadPartCopyRequest uploadPartCopyRequest =
                            new UploadPartCopyRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName);
                    uploadPartCopyRequest.setUploadId(uploadId);
                    uploadPartCopyRequest.setPartSize(size);
                    uploadPartCopyRequest.setBeginIndex(skipBytes);
                    uploadPartCopyRequest.setPartNumber(i + 1);
    
                    UploadPartCopyResult uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest);
                    // 将返回的分片ETag保存到partETags中。
                    partETags.add(uploadPartCopyResult.getPartETag());
                }
    
                // 提交分片拷贝任务。
                CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(
                        destinationBucketName, destinationObjectName, uploadId, partETags);
                CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
                System.out.println("versionId: "+completeMultipartUploadResult.getVersionId());
    
                // 查看源文件的标签信息。
                TagSet tagSet = ossClient.getObjectTagging(sourceBucketName, sourceObjectName);
                Map<String, String> getTags = tagSet.getAllTags();
                System.out.println("src object tagging: "+ getTags.toString());
    
                // 查看目标文件的标签信息。
                tagSet = ossClient.getObjectTagging(destinationBucketName, destinationObjectName);
                getTags = tagSet.getAllTags();
                System.out.println("dest object tagging: "+ getTags.toString());
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }

为软链接文件设置对象标签

以下代码用于为软链接文件设置对象标签。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.*;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";
        // 填写软链接完整路径,例如shortcut/myobject.txt。
        String symLink = "shortcut/myobject.txt";
        // 填写Object完整路径,Object完整路径中不能包含Bucket名称。例如exampledir/exampleobject.txt。
        String destinationObjectName = "exampledir/exampleobject.txt";
        // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
        String region = "cn-hangzhou";

        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 设置软链接的标签信息。
            Map<String, String> tags = new HashMap<String, String>();
            // 依次填写对象标签的键(例如owner)和值(例如John)。
            tags.put("owner", "John");
            tags.put("type", "document");

            // 创建上传文件元数据。
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setObjectTagging(tags);

            // 创建CreateSymlinkRequest。
            CreateSymlinkRequest createSymlinkRequest = new CreateSymlinkRequest(bucketName, symLink, destinationObjectName);

            // 设置元数据。
            createSymlinkRequest.setMetadata(metadata);

            // 创建软链接。
            ossClient.createSymlink(createSymlinkRequest);

            // 查看软链接的标签信息。
            TagSet tagSet = ossClient.getObjectTagging(bucketName, symLink);
            Map<String, String> getTags = tagSet.getAllTags();
            System.out.println("symLink tagging: "+ getTags.toString());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

相关文档

  • 关于设置对象标签的完整示例代码,请参见GitHub示例

  • 关于设置对象标签的API接口说明,请参见PutObjectTagging