Object Storage Service (OSS) içinde depolanan nesneler anahtarlardan, verilerden ve nesne meta verilerinden oluşur. Nesne meta verileri nesnenin niteliklerini tanımlar. Meta veriler standart HTTP üst bilgilerini ve kullanıcı meta verilerini içerir. Standart HTTP üst bilgilerini yapılandırarak nesne önbellek ilkesi veya zorunlu indirme ilkesi gibi özel HTTP istek ilkeleri oluşturabilirsiniz. Ayrıca bir nesneyi tanımlamak amacıyla o nesne için kullanıcı meta verileri ayarlayabilirsiniz.
Kullanım notları
Bu konuda Çin (Hangzhou) bölgesinin genel uç noktası kullanılmaktadır. Aynı bölgedeki diğer Alibaba Cloud hizmetlerinden OSS'ye erişmek için dahili uç noktayı kullanın. Desteklenen bölgeler ve uç noktalar hakkında daha fazla bilgi için bkz. Bölgeler ve uç noktalar.
Bu konuda erişim kimlik bilgileri ortam değişkenlerinden alınır. Daha fazla bilgi için bkz. Erişim kimlik bilgilerini yapılandırma.
Bu konu, bir OSS uç noktası kullanarak bir OSSClient örneği oluşturmayı gösterir. Özel alan adı kullanımı veya Security Token Service (STS) kimlik bilgileriyle kimlik doğrulama gibi alternatif yapılandırmalar için bkz. İstemci yapılandırması.
Nesne meta verilerini yapılandırmak için
oss:PutObjectiznine sahip olmanız gerekir. Nesne meta verilerini sorgulamak içinoss:GetObjectiznine sahip olmanız gerekir. Daha fazla bilgi için bkz. Özel bir ilke atama.
Nesne meta verilerini yapılandırma
Aşağıdaki kod, standart HTTP üst bilgileri ve kullanıcı meta verilerinin nasıl yapılandırılacağına ilişkin örnekler sunar.
-
Standart HTTP üst bilgilerini yapılandırma
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.common.utils.BinaryUtil; import com.aliyun.oss.common.utils.DateUtil; import com.aliyun.oss.model.ObjectMetadata; import java.io.ByteArrayInputStream; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the bucket name. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt. String objectName = "testfolder/exampleobject.txt"; String content = "Hello OSS"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release associated resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Add metadata for the uploaded object. ObjectMetadata meta = new ObjectMetadata(); String md5 = BinaryUtil.toBase64String(BinaryUtil.calculateMd5(content.getBytes())); // Enable MD5 verification. After MD5 verification is enabled, OSS calculates the MD5 hash of the uploaded object and compares this MD5 hash with that specified in the request. If the two values are different, an error is reported. meta.setContentMD5(md5); // Specify the type of content to upload. The browser determines the format and encoding type that are used to read the object based on the content type of the object. If the content type is not specified, a content type is generated based on the object name extension. If no extension is available, the default value application/octet-stream is used as the content type. meta.setContentType("text/plain; charset=utf-8"); // Configure the headers. For example, specify the storage class for uploaded files. meta.setHeader("x-oss-storage-class", StorageClass.Standard); // To enable the following configurations as needed, uncomment the corresponding lines. // Specify a name for the object when the content is downloaded. // meta.setContentDisposition("attachment; filename=\"DownloadFilename\""); // Specify the length of the object to upload. If the actual object length is greater than the specified length, the object is truncated. Only the content of the specified length is uploaded. If the actual object length is smaller than the specified length, all content of the object is uploaded. // meta.setContentLength(content.length()); // Specify the caching behavior of the web page when the content is downloaded. // meta.setCacheControl("Download Action"); // Specify the expiration time of the cache in UTC. // meta.setExpirationTime(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z")); // Specify the content encoding format when the content is downloaded. // meta.setContentEncoding("gzip"); // Upload the object. ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()), meta); } 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(); } } } }HTTP üst bilgileri hakkında daha fazla bilgi için bkz. RFC 2616.
-
Bir nesneyi tanımlamak üzere kullanıcı meta verilerini yapılandırma
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.ObjectMetadata; import java.io.ByteArrayInputStream; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the bucket name. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt. String objectName = "testfolder/exampleobject.txt"; String content = "Hello OSS"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release associated resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Add metadata for the object. ObjectMetadata meta = new ObjectMetadata(); // Specify custom metadata. We recommend that you use the Base64 encoding method. meta.addUserMetadata("key1", "value1"); meta.addUserMetadata("key2", "value2"); // Upload the object. ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()), meta); } 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(); } } } }Bir nesnenin meta verileri nesneyle birlikte indirilir. Bir nesne birden fazla meta veri parçasına sahip olabilir ancak meta verilerin toplam boyutu 8 KB'yi aşmamalıdır.
Nesne meta verilerini değiştirme
Aşağıdaki kod, bir nesnenin meta verilerinin nasıl değiştirileceğine ilişkin bir örnek sunar:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the source bucket.
String sourceBucketName = "yourSourceBucketName";
// Specify the full path of the source object.
String sourceObjectName = "yourSourceObjectName";
// Specify the name of the destination bucket. The destination bucket must be in the same region as the source bucket.
String destinationBucketName = "yourDestinationBucketName";
// Specify the full path of the destination object.
String destinationObjectName = "yourDestinationObjectName";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Specify that the source object is the same as the destination object. Call the ossClient.copyObject method to modify the object metadata.
CopyObjectRequest request = new CopyObjectRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName);
ObjectMetadata meta = new ObjectMetadata();
// Specify the type of content to upload. The browser determines the format and encoding type that are used to read the object based on the content type of the object. If the content type is not specified, a content type is generated based on the object name extension. If no extension is available, the default value application/octet-stream is used as the content type.
meta.setContentType("text/plain; charset=utf-8");
// Configure the headers. For example, specify the storage class for uploaded files.
meta.setHeader("x-oss-storage-class", StorageClass.Standard);
// To enable the following configurations as needed, uncomment the corresponding lines.
// Specify a name for the object when the content is downloaded.
// meta.setContentDisposition("attachment; filename=\"DownloadFilename\"");
// Specify the length of the object that can be uploaded. If the actual object length is greater than the specified length, only the specified length of the content is uploaded and the trailing part is truncated. If the actual object length is smaller than the specified length, all content of the object is uploaded.
// meta.setContentLength(content.length());
// Specify the caching behavior of the web page when the content is downloaded.
// meta.setCacheControl("Download Action");
// Specify the expiration time of the cache in UTC.
// meta.setExpirationTime(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
// Specify the content encoding format when the content is downloaded.
// meta.setContentEncoding("gzip");
// Specify custom metadata. We recommend that you use the Base64 encoding method.
meta.addUserMetadata("key1", "value1");
meta.addUserMetadata("key2", "value2");
request.setNewObjectMetadata(meta);
// Modify the object metadata.
ossClient.copyObject(request);
} 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();
}
}
}
}
Nesne meta verilerini sorgulama
Aşağıdaki tabloda nesne meta verilerini sorgulamak için kullanabileceğiniz yöntemler listelenmiştir.
|
|
|
|
|
|
|
|
|
Aşağıdaki kod, nesne meta verilerinin nasıl sorgulanacağına ilişkin bir örnek sunar:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.SimplifiedObjectMeta;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt.
String objectName = "testfolder/exampleobject.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Specify the bucket name and the full path of the object in the bucket.
// Query partial metadata of the object.
SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(bucketName, objectName);
System.out.println("Query partial metadata of the object");
System.out.println(objectMeta.getSize());
System.out.println(objectMeta.getETag());
System.out.println(objectMeta.getLastModified());
// Query object metadata, including the last access time of the object (X-Oss-Last-Access-Time), after the access tracking feature is enabled. You can only use OSS SDK for Java V3.16.0 or later to query X-Oss-Last-Access-Time.
System.out.println(objectMeta.getHeaders().get("x-oss-last-access-time"));
// Query all metadata of the object.
ObjectMetadata metadata = ossClient.getObjectMetadata(bucketName, objectName);
System.out.println("Query partial metadata of the object");
System.out.println(metadata.getContentType());
System.out.println(metadata.getLastModified());
System.out.println(metadata.getExpirationTime());
System.out.println(metadata.getETag());
System.out.println(metadata.getContentMD5());
System.out.println(metadata.getContentLength());
System.out.println(metadata.getObjectType());
System.out.println(metadata.getUserMetadata());
} 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();
}
}
}
}
İlgili başlıklar
Nesne meta verileri hakkında daha fazla bilgi için bkz. Nesne meta verilerini yönetme.
Nesne meta verilerini yapılandırmak ve sorgulamak için kullanılan eksiksiz örnek kodu görüntülemek üzere GitHub adresini ziyaret edin.
Basit yükleme sırasında nesne meta verilerini yapılandırmak için çağırabileceğiniz API işlemi hakkında daha fazla bilgi için bkz. PutObject.
Nesne meta verilerini sorgulamak için çağırabileceğiniz API işlemleri hakkında daha fazla bilgi için bkz. GetObjectMeta ve HeadObject.