Object Storage Service (OSS) uses object metadata to describe object attributes. Object metadata includes standard HTTP headers and user metadata. You can configure HTTP headers to create custom HTTP request policies, such as object cache policies and policies for forced object downloads. You can also configure the user metadata of an object to identify the purposes or attributes of the object.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS by using other Alibaba Cloud services in the same region as OSS, use an internal endpoint For more information about the regions and endpoints supported by OSS, see Regions and endpoints.
  • 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 STS, see Create an OSSClient instance.
  • To configure object metadata, you must have the oss:PutObject permission. To query object metadata, you must have the oss:GetObject permission. For more information, see Attach a custom policy to a RAM user.

Configure object metadata

The following sample code provides examples on how to configure the HTTP headers and user metadata of an object.

  • Configure HTTP headers

    The following code provides an example on how to configure the HTTP headers:

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    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";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // Specify the name of the bucket. 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";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            try {
                // Configure the metadata of the object. You can configure the HTTP headers of the object in the object metadata. 
                ObjectMetadata meta = new ObjectMetadata();
    
                String md5 = BinaryUtil.toBase64String(BinaryUtil.calculateMd5(content.getBytes()));
                // Enable MD5 verification for the object. After MD5 verification is enabled, OSS calculates the MD5 hash of the uploaded object and compares this MD5 hash with the MD5 hash that is specified in the request. If the two values are different, an error occurs. 
                meta.setContentMD5(md5);
                // Specify the type of the content that you want 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");
                // Specify the name of the object when the object is downloaded. 
                meta.setContentDisposition("attachment; filename=\"DownloadFilename\"");
                // Specify the length of the object that you want 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 parts of the object are 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 GMT. 
                meta.setExpirationTime(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
                // Specify the content encoding format when the content is downloaded. 
                meta.setContentEncoding("gzip");
                // Configure the HTTP header. 
                meta.setHeader("yourHeader", "yourHeaderValue");
    
                // 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.

  • Configure user metadata

    You can configure user metadata of an object to describe the object.

    The following code provides an example on how to configure the user metadata of an object:

    package com.aliyun.oss.demo;
    
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    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";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // Specify the name of the bucket. 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";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            try {
                // Configure object metadata. 
                ObjectMetadata meta = new ObjectMetadata();
                // Set the property parameter of user metadata to property-value. We recommend that you use the Base64 encoding method. 
                meta.addUserMetadata("property", "property-value");
    
                // 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 along with the object. An object can have multiple pieces of object metadata. The total size of metadata of an object cannot exceed 8 KB.

Modify object metadata

The following code provides an example on how to modify the metadata of an object:

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
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";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // 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";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // Replace the source object with the destination object. Call ossClient.copyObject to modify object metadata. 
            CopyObjectRequest request = new CopyObjectRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName);

            ObjectMetadata meta = new ObjectMetadata();
            // Specify the type of the content that you want 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");
            // Specify the name of the object when the object is downloaded. 
            meta.setContentDisposition("Download File Name");
            // 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 GMT. 
            meta.setExpirationTime(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
            // Specify the content encoding format when the content is downloaded. 
            meta.setContentEncoding("gzip");
            // Configure a header. 
            meta.setHeader("<yourHeader>", "<yourHeaderValue>");
            // Set the property parameter of user metadata to property-value. 
            meta.addUserMetadata("property", "property-value");
            request.setNewObjectMetadata(meta);

            // Modify the metadata of the object. 
            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();
            }
        }
    }
}            

Query object metadata

The following table provides the methods that you can use to query object metadata.
MethodDescription
ossClient.getSimplifiedObjectMetaQueries the values of ETag, Size, and LastModified of the object by calling the GetObjectMeta operation.
ossClient.getObjectMetadataQueries all object metadata by calling the HeadObject operation.

The following code provides an example on how to query object metadata:

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
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";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. 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";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        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(objectMeta.getSize());
            System.out.println(objectMeta.getETag());
            System.out.println(objectMeta.getLastModified());
            // Query the object metadata including the last access time (X-Oss-Last-Access-Time) after access tracking 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(metadata.getContentType());
            System.out.println(metadata.getLastModified());
            System.out.println(metadata.getExpirationTime());
        } 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 the complete sample code that is used to configure and query object metadata, visit GitHub.
  • For more information about the API operation that you can call to configure object metadata in a simple upload task, see PutObject.
  • For more information about the API operations that you can call to query the metadata of an object, see GetObjectMeta and HeadObject.