Tous les produits
Search
Centre de documentation

Object Storage Service:Gérer les métadonnées d'objet (SDK OSS pour Java 1.0)

Dernière mise à jour :Sep 24, 2026

Les objets stockés dans Object Storage Service (OSS) se composent de clés, de données et de métadonnées d'objet. Les métadonnées d'objet décrivent les attributs de l'objet. Elles incluent des en-têtes HTTP standard et des métadonnées utilisateur. Vous pouvez définir des politiques de requête HTTP personnalisées, telles que des politiques de mise en cache ou de téléchargement forcé d'objets, en configurant les en-têtes HTTP standard. Vous pouvez également configurer des métadonnées utilisateur pour identifier la finalité ou les attributs d'un objet.

Notes d'utilisation

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un point de terminaison interne. Pour plus de détails sur les régions et points de terminaison pris en charge, consultez Régions et points de terminaison.

  • Dans cette rubrique, les informations d'identification d'accès sont obtenues à partir des variables d'environnement. Pour plus d'informations, consultez Configurer les informations d'identification d'accès.

  • Cette rubrique montre comment créer une instance OSSClient avec un point de terminaison OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification avec des informations d'identification du Security Token Service (STS), consultez Configuration du client.

  • Pour configurer les métadonnées d'objet, vous devez disposer de l'autorisation oss:PutObject. Pour interroger les métadonnées d'objet, vous devez disposer de l'autorisation oss:GetObject. Pour plus d'informations, consultez Accorder une politique personnalisée.

Configurer les métadonnées d'objet

Le code suivant fournit des exemples de configuration des en-têtes HTTP standard et des métadonnées utilisateur.

  • Configurer les en-têtes HTTP standard

    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 {
                // 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; charset=utf-8");
                // Configure the headers. For example, specify the storage class for uploaded files.
                meta.setHeader("x-oss-storage-class", StorageClass.Standard);
                
                // To enable the following configurations as needed, uncomment the corresponding lines.
                
                // 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");
    
                // 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();
                }
            }
        }
    }               

    Pour plus d'informations sur les en-têtes HTTP, consultez RFC 2616.

  • Configurer les métadonnées utilisateur pour décrire un objet

    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 {
                // Add metadata for the object. 
                ObjectMetadata meta = new ObjectMetadata();
                // Specify custom metadata. We recommend that you use the Base64 encoding method. 
                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();
                }
            }
        }
    }                    

    Les métadonnées d'un objet sont téléchargées avec l'objet. Un objet peut comporter plusieurs éléments de métadonnées, dont la taille totale ne doit pas dépasser 8 Ko.

Modifier les métadonnées d'objet

Le code suivant montre comment modifier les métadonnées d'un objet :

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. 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 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 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; charset=utf-8");
            // Configure the headers. For example, specify the storage class for uploaded files.
            meta.setHeader("x-oss-storage-class", StorageClass.Standard);
            
            // To enable the following configurations as needed, uncomment the corresponding lines.
            
            // Specify a name for the object when the content is downloaded. 
            // meta.setContentDisposition("attachment; filename=\"DownloadFilename\"");
            // Specify the length of the object that can be uploaded. If the actual object length is greater than the specified length, only the specified length of the content is uploaded and the trailing part is truncated. 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");
 
            // Specify custom metadata. We recommend that you use the Base64 encoding method. 
            meta.addUserMetadata("key1", "value1");
            meta.addUserMetadata("key2", "value2");
            
            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();
            }
        }
    }
}            

Interroger les métadonnées d'objet

Le tableau suivant répertorie les méthodes permettant d'interroger les métadonnées d'objet.

Méthode

Description

ossClient.getSimplifiedObjectMeta

Interroge les valeurs ETag, Size et LastModified de l'objet en appelant l'opération GetObjectMeta.

ossClient.getObjectMetadata

Interroge toutes les métadonnées de l'objet en appelant l'opération HeadObject.

Le code suivant montre comment interroger les métadonnées d'objet :

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 in the bucket. 
            // Query partial metadata of the object. 
            SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(bucketName, objectName);
            System.out.println("Query partial metadata of the object");
            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("Query partial 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();
            }
        }
    }
}

Références

  • Pour plus d'informations sur les métadonnées d'objet, consultez Gérer les métadonnées d'objet.

  • Pour obtenir l'exemple de code complet utilisé pour configurer et interroger les métadonnées d'objet, visitez GitHub.

  • Pour plus d'informations sur l'opération API à appeler pour configurer les métadonnées d'objet lors d'un chargement simple, consultez PutObject.

  • Pour plus d'informations sur les opérations API à appeler pour interroger les métadonnées d'objet, consultez GetObjectMeta et HeadObject.