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 configure standard HTTP headers to create custom HTTP request policies, such as object cache policies and forced object download policies. You can also configure 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 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 code provides examples of how to set standard HTTP headers and user metadata.
Set standard HTTP headers
The following code provides an example of 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 { // 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 { // 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 MD5 validation is enabled, OSS calculates the MD5 hash of the uploaded object and compares this MD5 hash with the one you provide. If the two values are different, an exception is thrown. meta.setContentMD5(md5); // Specify the content type of the object to upload. The content type determines how the browser reads the object and in which encoding format. 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. 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 of code based on your needs. // 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 actual object length is greater than the specified length, the object is truncated to the specified length. If the actual object length is smaller than the specified length, the 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 in GMT. // 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 user metadata
You can set user metadata to describe an object.
The following code provides an example of how to set user 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 { // 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 { // 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(); } } } }When you download an object, its metadata is also downloaded. An object can have multiple metadata entries. The total size of the metadata cannot exceed 8 KB.
Modify object metadata
The following code provides an example of 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 {
// 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 that is 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 {
// Set the source object to be the same as the destination object, and 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 upload. The content type determines how the browser reads the object and in which encoding format. 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.
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 of code based on your needs.
// 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 actual object length is greater than the specified length, the object is truncated to the specified length. If the actual object length is smaller than the specified length, the 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 in GMT.
// 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();
}
}
}
} Retrieve object metadata
You can retrieve object metadata using the following two methods.
Method | Description |
ossClient.getSimplifiedObjectMeta | Retrieves the ETag, Size, and LastModified time of an object. This method corresponds to the GetObjectMeta API operation. |
ossClient.getObjectMetadata | Retrieves all metadata of an object. This method corresponds to the HeadObject API operation. |
The following code provides an example of 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 {
// 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.
// Retrieve partial metadata of the object.
SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(bucketName, objectName);
System.out.println("Retrieve partial metadata of the object");
System.out.println(objectMeta.getSize());
System.out.println(objectMeta.getETag());
System.out.println(objectMeta.getLastModified());
// After the access tracking feature is enabled, you can retrieve object metadata that includes the last access time (X-Oss-Last-Access-Time). Only OSS SDK for Java 3.16.0 and later versions support retrieving X-Oss-Last-Access-Time.
System.out.println(objectMeta.getHeaders().get("x-oss-last-access-time"));
// Retrieve all metadata of the object.
ObjectMetadata metadata = ossClient.getObjectMetadata(bucketName, objectName);
System.out.println("Retrieve 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 on how to set and retrieve object metadata, see 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.