Objects stored in Object Storage Service (OSS) consist of keys, data, and object metadata. Object metadata describes the attributes of an object and includes standard HTTP headers and user metadata. You can set standard HTTP headers to create custom HTTP request policies, such as object cache and forced download policies. You can also set user metadata for an object to identify its purpose or attributes.
Usage notes
In this topic, the public endpoint of the China (Hangzhou) region is used. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For details about supported regions and endpoints, see OSS regions and endpoints.
In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.
In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Configuration examples for common scenarios.
To set object metadata, you must have the
oss:PutObjectpermission. To retrieve object metadata, you must have theoss:GetObjectpermission. For more information, see Attach a custom policy to a RAM user.
Set object metadata
The following examples show how to set standard HTTP headers and custom metadata.
Set standard HTTP headers
The following code shows how to set standard HTTP headers.
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 { // The endpoint of the China (Hangzhou) region is used as an example. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Get access credentials from environment variables. Before you run this 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. For example, examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. For example, testfolder/exampleobject.txt. String objectName = "testfolder/exampleobject.txt"; String content = "Hello OSS"; // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // When the OSSClient instance is no longer used, call the shutdown method to release its resources. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Create metadata for the object to be uploaded. ObjectMetadata meta = new ObjectMetadata(); String md5 = BinaryUtil.toBase64String(BinaryUtil.calculateMd5(content.getBytes())); // Enable MD5 validation for the object content. After you enable this feature, OSS compares the MD5 hash of the uploaded object with the MD5 hash that you provide. If the two hash values are different, an exception is thrown. meta.setContentMD5(md5); // Specify the content type of the object to be uploaded. The content type determines how the browser reads the object. If you do not specify this parameter, the content type is generated based on the object's file extension. If the object has no file extension, the default value application/octet-stream is used. meta.setContentType("text/plain; charset=utf-8"); // Set the header. For example, set the storage class for the uploaded object. meta.setHeader("x-oss-storage-class", StorageClass.Standard); // Uncomment the following lines as needed. // Set the name of the object when it is downloaded. // meta.setContentDisposition("attachment; filename=\"DownloadFilename\""); // Set the length of the object to upload. If the object is larger than this length, it is truncated. If the object is smaller, its actual length is used. // meta.setContentLength(content.length()); // Set the caching behavior of the web page when the object is downloaded. // meta.setCacheControl("Download Action"); // Set the cache expiration time. The time must be in GMT format. // meta.setExpirationTime(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z")); // Set the encoding format of the object when it 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(); } } } }For more information about HTTP headers, see RFC 2616.
Set custom metadata
You can set custom metadata to describe an object.
The following code shows how to set custom metadata for an object.
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 { // The endpoint of the China (Hangzhou) region is used as an example. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Get access credentials from environment variables. Before you run this 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. For example, examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. For example, testfolder/exampleobject.txt. String objectName = "testfolder/exampleobject.txt"; String content = "Hello OSS"; // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // When the OSSClient instance is no longer used, call the shutdown method to release its resources. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Create object metadata. ObjectMetadata meta = new ObjectMetadata(); // Set custom metadata. We recommend that you use Base64 encoding. 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(); } } } }The metadata of an object is downloaded with the object. An object can have multiple metadata entries. The total size of the metadata cannot exceed 8 KB.
Modify object metadata
The following code shows how to modify the metadata of an object.
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 {
// The endpoint of the China (Hangzhou) region is used as an example. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Get access credentials from environment variables. Before you run this 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 where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// When the OSSClient instance is no longer used, call the shutdown method to release its resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Set the source object to be 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 content type of the object to be uploaded. The content type determines how the browser reads the object. If you do not specify this parameter, the content type is generated based on the object's file extension. If the object has no file extension, the default value application/octet-stream is used.
meta.setContentType("text/plain; charset=utf-8");
// Set the header. For example, set the storage class for the uploaded object.
meta.setHeader("x-oss-storage-class", StorageClass.Standard);
// Uncomment the following lines as needed.
// Set the name of the object when it is downloaded.
// meta.setContentDisposition("attachment; filename=\"DownloadFilename\"");
// Set the length of the object to upload. If the object is larger than this length, it is truncated. If the object is smaller, its actual length is used.
// meta.setContentLength(content.length());
// Set the caching behavior of the web page when the object is downloaded.
// meta.setCacheControl("Download Action");
// Set the cache expiration time. The time must be in GMT format.
// meta.setExpirationTime(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
// Set the encoding format of the object when it is downloaded.
// meta.setContentEncoding("gzip");
// Set custom metadata.
meta.addUserMetadata("key1", "value1");
meta.addUserMetadata("key2", "value2");
request.setNewObjectMetadata(meta);
// Modify the 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();
}
}
}
} Get object metadata
You can use the following two methods to retrieve object metadata.
Method | Description |
ossClient.getSimplifiedObjectMeta | Gets the ETag, Size, and LastModified time of the object. This method corresponds to the GetObjectMeta API operation. |
ossClient.getObjectMetadata | Gets all metadata of the object. This method corresponds to the HeadObject API operation. |
The following code shows how to retrieve object metadata.
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 {
// The endpoint of the China (Hangzhou) region is used as an example. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Get access credentials from environment variables. Before you run this 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. For example, examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. For example, testfolder/exampleobject.txt.
String objectName = "testfolder/exampleobject.txt";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// When the OSSClient instance is no longer used, call the shutdown method to release its resources.
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.
// Get partial metadata of the object.
SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(bucketName, objectName);
System.out.println("Get partial metadata of the object");
System.out.println(objectMeta.getSize());
System.out.println(objectMeta.getETag());
System.out.println(objectMeta.getLastModified());
// After you enable access tracking, you can get object metadata that includes the last access time (X-Oss-Last-Access-Time). You can get X-Oss-Last-Access-Time only if you use Java SDK 3.16.0 or later.
System.out.println(objectMeta.getHeaders().get("x-oss-last-access-time"));
// Get all metadata of the object.
ObjectMetadata metadata = ossClient.getObjectMetadata(bucketName, objectName);
System.out.println("Get all 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();
}
}
}
}References
For more information about object metadata, see Manage object metadata.
For the complete sample code that is used to set and retrieve object metadata, see the GitHub example.
For more information about the API operation that you can call to set object metadata during a simple upload, see PutObject.
For more information about the API operations that you can call to retrieve object metadata, see GetObjectMeta and HeadObject.