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。