全部產品
Search
文件中心

Object Storage Service:Java設定對象標籤

更新時間:Oct 25, 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