All Products
Search
Document Center

Object Storage Service:Manage object metadata

Last Updated:Jan 30, 2024

Objects stored in Object Storage Service (OSS) consist of keys, data, and object metadata. Object metadata describes object attributes. Object metadata includes standard HTTP headers and user metadata. You can create custom HTTP request policies such as object cache policies and forced object download policies by configuring standard HTTP headers. You can also configure user metadata for 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 from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS 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 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 code provides examples on how to configure standard HTTP headers and user metadata.

  • Configure standard HTTP headers

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    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";
            // 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";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            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");
                // 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");
                // Configure the HTTP headers. 
                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 to describe an object

    package com.aliyun.oss.demo;
    
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    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";
            // 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";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            try {
                // Add metadata for 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);            
            } 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 metadata, with the total size of the metadata no more than 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.common.auth.*;
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";
        // 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";

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

        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");
            // Specify a name for the object when the content 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 UTC. 
            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 headers. 
            meta.setHeader("<yourHeader>", "<yourHeaderValue>");
            // Set the property parameter of user metadata to property-value. 
            meta.addUserMetadata("property", "property-value");
            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();
            }
        }
    }
}            

Query object metadata

The following table lists the methods that you can use to query object metadata.

Method

Description

ossClient.getSimplifiedObjectMeta

Queries the values of ETag, Size, and LastModified of the object by calling the GetObjectMeta operation.

ossClient.getObjectMetadata

Queries all metadata of the object 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.common.auth.*;
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";
        // 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";

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

        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 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(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 more information about object metadata, see Manage object metadata.

  • 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 during simple upload, see PutObject.

  • For more information about the API operation that you can call to query object metadata, see GetObjectMeta and HeadObject.