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 customize HTTP request policies, such as cache policies and policies for forced object download. You can also configure user metadata to identify the purposes or attributes of objects.

Configure object metadata

The following examples show 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 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.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 Object Storage Service (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 bucket name. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. The full path of the object cannot contain the bucket name. 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 {
                // Create 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. After MD5 verification is enabled, OSS calculates the MD5 hash of the object and compares this MD5 hash with the MD5 hash provided 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 a name for the object when the content is downloaded. 
                meta.setContentDisposition("attachment; filename=\"DownloadFilename\"");
                // Specify the length of the object content to upload. If the actual object length is greater than the configured length, the object is truncated. Only content of the configured length is uploaded. If the configured length is greater than the actual object length, all parts of the object are uploaded. 
                meta.setContentLength(content.length());
                // Specify the caching behavior of the website 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("utf-8");
                // 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 the 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 bucket name. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. The full path of the object cannot contain the bucket name. 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 {
                // Create the metadata of the object. 
                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);
    
                // Query the metadata of the object. 
                ossClient.getObjectMetadata(bucketName, objectName);
            } 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 object metadata 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 a name for the object when the content is downloaded. 
            meta.setContentDisposition("Download File Name");
            // Specify the caching behavior of the website 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("utf-8");
            // Configure the 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 you can use to query the metadata of an object.

Method Description Advantage
ossClient.getSimplifiedObjectMeta Queries part of object metadata such as the ETag, Size, and LastModified (the last modified time) values of the object. More lightweight and faster
ossClient.getObjectMetadata Queries all object metadata. N/A

The following code provides an example on how to query 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.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 bucket name. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. The full path of the object cannot contain the bucket name. 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 part of object metadata. 
            SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(bucketName, objectName);
            System.out.println(objectMeta.getSize());
            System.out.println(objectMeta.getETag());
            System.out.println(objectMeta.getLastModified());

            // Query all object metadata. 
            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 simple upload, see PutObject.
  • For more information about the API operation that you can call to query object metadata, see GetObjectMeta.