Tous les produits
Search
Centre de documentation

Object Storage Service:Gérer les métadonnées d'objet

Dernière mise à jour :Sep 22, 2026

Les métadonnées d'objet comprennent des en-têtes HTTP standard et des métadonnées utilisateur. Configurez les en-têtes HTTP pour contrôler la mise en cache, le type de contenu et le comportement de téléchargement. Ajoutez des métadonnées utilisateur pour étiqueter les objets avec des paires clé-valeur personnalisées.

En-têtes HTTP standard

OSS stocke les en-têtes HTTP standard suivants pour chaque objet téléversé.

En-tête HTTP standard

Description

Content-Type

Le type multimédia de l'objet. Les navigateurs utilisent cet en-tête pour déterminer comment lire l'objet. Si vous ne le spécifiez pas, OSS attribue une valeur basée sur l'extension du fichier ou utilise la valeur par défaut application/octet-stream. Pour plus d'informations, consultez Comment configurer l'en-tête Content-Type ?

Content-Encoding

La méthode d'encodage appliquée à l'objet. Définissez cet en-tête pour qu'il corresponde à l'encodage réel. En cas de non-concordance, le navigateur peut échouer à analyser ou à télécharger l'objet. Laissez ce champ vide si l'objet n'est pas encodé. Valeurs valides :

  • identity (par défaut) : Aucune compression ni aucun encodage.

  • gzip : Encodé avec l'algorithme LZ77 et un CRC 32 bits.

  • compress : Encodé avec l'algorithme LZW.

  • deflate : Encodé avec zlib et l'algorithme deflate.

  • br : Encodé avec l'algorithme Brotli.

Content-Encoding est défini dans RFC 2616.

Important

Si vous souhaitez que les objets de pages web statiques, tels que les objets HTML, JavaScript, XML et JSON, soient compressés au format GZIP lors de leur accès, vous devez laisser cet en-tête vide et ajouter l'en-tête Accept-Encoding: gzip à votre requête.

Content-Language

La langue du contenu de l'objet. Par exemple, définissez cet en-tête sur zh-CN pour un contenu en chinois simplifié.

Content-Disposition

Contrôle si le navigateur affiche ou télécharge l'objet. Valeurs valides :

  • Content-Disposition:inline : Affiche l'objet dans le navigateur.

  • Content-Disposition:attachment : Télécharge l'objet avec son nom d'origine.

  • Content-Disposition:attachment; filename="yourFileName" : Télécharge l'objet avec un nom de fichier personnalisé.

    yourFileName correspond au nom de fichier personnalisé, par exemple example.jpg.

Lors du téléchargement d'objets en tant que pièces jointes, tenez compte des points suivants :

Remarque
  • Si le nom de l'objet contient des caractères spéciaux tels que des astérisques () ou des barres obliques (/), le nom du fichier téléchargé peut être échappé. Par exemple, si vous téléchargez example.jpg sur votre ordinateur local, example*.jpg peut être échappé en example_.jpg.

  • Pour éviter que les noms de fichiers contenant des caractères non ASCII ne s'affichent incorrectement, encodez-les au format URL. Par exemple, pour télécharger l'objet Test.txt avec son nom d'origine Test.txt, définissez l'en-tête Content-Disposition sur attachment;filename=%E6%B5%8B%E8%AF%95.txt;filename=UTF-8''%E6%B5%8B%E8%AF%95.txt, ce qui découle de "attachment;filename="+URLEncoder.encode("Test","UTF-8")+".txt;filename=UTF-8''"+URLEncoder.encode("Test","UTF-8")+".txt".

Le fait qu'un objet soit prévisualisé ou téléchargé en tant que pièce jointe dépend de la date de création du bucket, de la date d'activation d'OSS et du type de nom de domaine. Pour plus d'informations, consultez Que faire si un objet image est téléchargé en tant que pièce jointe mais ne peut pas être prévisualisé lorsque j'accède à l'objet image via son URL ?

Cache-Control

Remarque

Si Cache-Control n'est pas défini, OSS omet ce champ de l'en-tête de réponse. Le navigateur applique alors sa propre politique de mise en cache par défaut.

Contrôle le comportement de mise en cache de l'objet. Valeurs valides :

  • no-cache : Le cache doit revalider auprès du serveur d'origine avant de servir le contenu.

  • no-store : Aucune mise en cache de l'objet.

  • public : L'objet peut être mis en cache par n'importe quel cache.

  • private : L'objet est mis en cache uniquement sur le client.

  • max-age=<seconds> : La période de validité du cache en secondes. Disponible uniquement dans HTTP 1.1.

Expires

L'heure d'expiration du cache en UTC. Exemple : 2022-10-12T00:00:00.000Z. Si max-age=<seconds> est inclus dans les paramètres de l'en-tête Cache-Control, max-age=<seconds> est prioritaire sur la valeur de Expires.

Last-Modified

La dernière heure de modification de l'objet, en UTC. L'en-tête Last-Modified est mis à jour automatiquement par OSS et ne peut pas être modifié manuellement. Pour plus d'informations, consultez Quelles sont les opérations qui affectent l'attribut LastModified des objets OSS ?

Remarque

La console OSS convertit l'UTC en votre fuseau horaire local. Par exemple, un objet mis à jour pour la dernière fois à 13:31:54 UTC le 28 février 2024 s'affiche à 21:31:54 dans le fuseau horaire UTC+8.

Content-Length

La taille de l'objet. Unité : octets.

Métadonnées utilisateur

Ajoutez des métadonnées utilisateur lors du téléversement d'objets pour identifier leur objectif ou leurs attributs.

  • Un objet prend en charge plusieurs en-têtes de métadonnées utilisateur, jusqu'à 8 Ko au total.

  • Les en-têtes de métadonnées utilisateur sont des paires clé-valeur. Chaque nom d'en-tête doit commencer par x-oss-meta-. Par exemple, x-oss-meta-last-modified:20210506 indique que le fichier local a été modifié pour la dernière fois le 6 mai 2021.

  • Les opérations GetObject et HeadObject renvoient les métadonnées utilisateur sous forme d'en-têtes HTTP.

Procédure

Utiliser la console OSS

La console OSS permet de configurer les métadonnées pour jusqu'à 100 objets à la fois.

  1. Connectez-vous à la console OSS.

  2. Dans le volet de navigation de gauche, cliquez sur Buckets. Sur la page qui s'affiche, cliquez sur le nom du bucket cible.

  3. Dans le volet de navigation de gauche, choisissez Object Management > Objects.

  4. Configurez les en-têtes HTTP standard et les métadonnées utilisateur.

    • Configurer les en-têtes HTTP pour plusieurs objets simultanément

      Sélectionnez les objets pour lesquels vous souhaitez configurer les métadonnées et cliquez sur Set Object Metadata.

    • Configurer les en-têtes HTTP pour un seul objet

      Recherchez l'objet dans la liste des objets et choisissez more > Set Object Metadata.

  5. Cliquez sur OK.

  6. OSS ne prend pas en charge l'héritage par défaut de Cache-Control au niveau du bucket. Vous ne pouvez pas configurer une valeur Cache-Control unifiée pour un bucket et faire en sorte que cette valeur soit automatiquement héritée par les objets téléversés ultérieurement. Pour configurer par lot l'en-tête Cache-Control des objets existants, vous pouvez également utiliser ossutil :

    ossutil set-props oss://bucketname/prefix -r -f --cache-control max-age=86400

    Pour plus d'informations, consultez set-props (configurer les propriétés des objets).

    Opérations courantes dans ossbrowser

Utiliser ossbrowser

ossbrowser prend en charge les mêmes opérations au niveau des objets que la console OSS. Pour plus d'informations, consultez 常用操作.

Utiliser les SDK OSS

Le code suivant montre comment configurer les métadonnées d'objet avec les SDK OSS. Pour les SDK dans d'autres langages, consultez Présentation.

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();
            }
        }
    }
}               
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;

// 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.  
$provider = new EnvironmentVariableCredentialsProvider();
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
$endpoint = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
$object = "exampledir/exampleobject.txt";
$content = file_get_contents(__FILE__);
$options = array(
    OssClient::OSS_HEADERS => array(
        'Expires' => '2012-10-01 08:00:00',
        'Content-Disposition' => 'attachment; filename="xxxxxx"',
        'x-oss-meta-self-define-title' => 'user define meta info',
    ));
try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);
    // Configure object metadata when you upload the object. 
    $ossClient->putObject($bucket, $object, $content, $options);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");
            
const OSS = require('ali-oss');
const path = require('path');

const client = new OSS({
  // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: 'oss-cn-hangzhou',
  // Use Signature V4.
  authorizationV4: true,
  // Set yourBucketName to the name of the bucket.
  bucket: 'yourBucketName',
  // Set yourEndpoint to the Internet endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
});

async function put() {
  try {
    // Set metadata as the meta property of the options object.
    let result = await client.put('object-name', path.normalize('D:\\localpath\\examplefile.txt'), {
      meta: {
        year: '2025',  // The metadata value must be a string.
        people: 'mary'
      }
    });
  console.log(result);
  } catch (e) {
    console.log(e);
  }
}

put();
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# 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. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
object_name = 'exampledir/exampleobject.txt'
# Specify the string that you want to upload. 
content = '{"age": 1}'
# Configure HTTP headers. For example, set the Content-Type header to 'application/json; charset=utf-8'. 
bucket.put_object(object_name, content, headers={'Content-Type': 'application/json; charset=utf-8'})
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Util;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// 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. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. 
var objectName = "exampleobject.txt";
// Specify the full path of the local object that you want to upload. By default, if you do not specify the full path of the local object, the local object is uploaded from the path of the project to which the sample program belongs. 
var localFilename = "D:\\localpath\\examplefile.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.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    using (var fs = File.Open(localFilename, FileMode.Open))
    {
        // Create metadata for the object. You can configure HTTP headers for the object. 
        var metadata = new ObjectMetadata()
        {
            // Specify the content type of the object. 
            ContentType = "text/html",
            // Specify the expiration time of the cache in UTC. 
            ExpirationTime = DateTime.Parse("2025-10-12T00:00:00.000Z"),
        };
        // Specify the length of the object content 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. 
        metadata.ContentLength = fs.Length;
        // Specify the caching behavior of the web page when the object is downloaded. 
        metadata.CacheControl = "No-Cache";
        // Set mykey1 to myval1. 
        metadata.UserMetadata.Add("mykey1", "myval1");
        // Set mykey2 to myval2. 
        metadata.UserMetadata.Add("mykey2", "myval2");
        var saveAsFilename = "Filetest123.txt";
        var contentDisposition = string.Format("attachment;filename*=utf-8''{0}", HttpUtils.EncodeUri(saveAsFilename, "utf-8"));
        // Specify a default object name when the required content is saved as an object. 
        metadata.ContentDisposition = contentDisposition;
        // Upload the object and configure object metadata. 
        client.PutObject(bucketName, objectName, fs, metadata);
        Console.WriteLine("Put object succeeded");
        // Query object metadata. 
        var oldMeta = client.GetObjectMetadata(bucketName, objectName);
        // Configure new object metadata. 
        var newMeta = new ObjectMetadata()
        {
            ContentType = "application/octet-stream",
            ExpirationTime = DateTime.Parse("2035-11-11T00:00:00.000Z"),
            // Specify the content encoding format of the object when the object is downloaded. 
            ContentEncoding = null,
            CacheControl = ""
        };
        // Configure user metadata. 
        newMeta.UserMetadata.Add("author", "oss");
        newMeta.UserMetadata.Add("flag", "my-flag");
        newMeta.UserMetadata.Add("mykey2", "myval2-modified-value");
        // Use the ModifyObjectMeta method to modify the object metadata. 
        client.ModifyObjectMeta(bucketName, objectName, newMeta);
    }
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}
// Create a request to synchronously get object metadata.
// Specify the bucket name, such as examplebucket, and the full path of the object, such as exampledir/exampleobject.txt. The full path cannot contain the bucket name.
HeadObjectRequest head = new HeadObjectRequest("examplebucket", "exampledir/exampleobject.txt");

// Get the object metadata.
OSSAsyncTask task = oss.asyncHeadObject(head, new OSSCompletedCallback<HeadObjectRequest, HeadObjectResult>() {
    @Override
    public void onSuccess(HeadObjectRequest request, HeadObjectResult result) {
    
    // Get the object length.
        Log.d("headObject", "object Size: " + result.getMetadata().getContentLength()); 
    // Get the object type.
        Log.d("headObject", "object Content Type: " + result.getMetadata().getContentType()); 
    }

    @Override
    public void onFailure(HeadObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Request exception.
        if (clientExcepion != null) {
            // A client exception occurred, such as a network error.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // A server exception occurred.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

// task.waitUntilFinished(); // Wait for the task to complete.
OSSHeadObjectRequest * request = [OSSHeadObjectRequest new];
// Specify the bucket name. For example, examplebucket.
request.bucketName = @"examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt.
request.objectKey = @"exampledir/exampleobject.txt";

OSSTask * headTask = [client headObject:request];

[headTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"head object success!");
        OSSHeadObjectResult * result = task.result;
        NSLog(@"header fields: %@", result.httpResponseHeaderFields);
        for (NSString * key in result.objectMeta) {
            NSLog(@"ObjectMeta: %@ - %@", key, [result.objectMeta objectForKey:key]);
        }
    } else {
        NSLog(@"head object failed, error: %@" ,task.error);
    }
    return nil;
}];
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{

    /* Initialize OSS account information. */
    
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

    /* Initialize network resources. */
    InitializeSdk();
  
    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Set HTTP headers. */
    auto meta = ObjectMetaData();
    meta.setContentType("text/plain");
    meta.setCacheControl("max-age=3");
    /* Set custom object metadata. */
    meta.UserMetaData()["meta"] = "meta-value";

    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
    *content << "Thank you for using Alibaba Cloud Object Storage Service!";
    auto outcome = client.PutObject(BucketName, ObjectName, content, meta);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "PutObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, for the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name. For example, examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
const char *object_content= "hello world";
/* Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Initialize an aos_string_t type with a char* string. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // Configure the following two additional parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether a CNAME is used. A value of 0 indicates that no CNAME is used. */
    options->config->is_cname = 0;
    /* Set network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method at the program entry to initialize global resources such as the network and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* The memory pool for memory management is equivalent to apr_pool_t. The implementation code is in the apr library. */
    aos_pool_t *pool;
    /* Create a new memory pool. The second parameter is NULL, which indicates that the new pool does not inherit from another memory pool. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter contains global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate memory for options in the memory pool. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize the client options oss_client_options. */
    init_options(oss_client_options);
    /* Initialize parameters. */
    aos_string_t bucket;
    aos_string_t object;
    aos_table_t *headers;
    aos_list_t buffer;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    aos_buf_t *content = NULL;
    char *content_length_str = NULL;
    char *object_type = NULL;
    char *object_author = NULL;
    int64_t content_length = 0;
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    headers = aos_table_make(pool, 2);
    /* Set user-defined metadata. */
    apr_table_set(headers, "Expires", "Fri, 28 Feb 2032 05:38:42 GMT"); 
    apr_table_set(headers, "x-oss-meta-author", "oss");
    aos_list_init(&buffer);
    content = aos_buf_pack(oss_client_options->pool, object_content, strlen(object_content));
    aos_list_add_tail(&content->node, &buffer);
    /* Upload the object from the buffer. */
    resp_status = oss_put_object_from_buffer(oss_client_options, &bucket, &object, 
               &buffer, headers, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("put object from buffer with md5 succeeded\n");
    } else {
        printf("put object from buffer with md5 failed\n");
    }
    /* Get the object metadata. */
    resp_status = oss_get_object_meta(oss_client_options, &bucket, &object, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        content_length_str = (char*)apr_table_get(resp_headers, OSS_CONTENT_LENGTH);
        if (content_length_str != NULL) {
            content_length = atol(content_length_str);
        }
        object_author = (char*)apr_table_get(resp_headers, OSS_AUTHORIZATION);
        object_type = (char*)apr_table_get(resp_headers, OSS_OBJECT_TYPE);
        printf("get object meta succeeded, object author:%s, object type:%s, content_length:%ld\n", object_author, object_type, content_length);
    } else {
        printf("req:%s, get object meta failed\n", resp_status->req_id);
    }
    /* Release the memory pool. This releases the memory allocated to resources during the request. */
    aos_pool_destroy(pool);
    /* Release the previously allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
  # Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)

# Specify the bucket name. Example: examplebucket.
bucket = client.get_bucket('examplebucket')

# Set object metadata during a simple upload.
bucket.put_object(
  'my-object-1',
  :file => 'local-file',
  :metas => {'year' => '2016', 'people' => 'mary'})

# Set object metadata during an append upload.
bucket.append_object(
  'my-object-2', 0,
  :file => 'local-file',
  :metas => {'year' => '2016', 'people' => 'mary'})

# Set object metadata during a resumable upload.
bucket.resumable_upload(
  'my-object',
  'local-file',
  :metas => {'year' => '2016', 'people' => 'mary'})          
package main

import (
	"context"
	"flag"
	"log"
	"strings"
	"time"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The storage region.
	bucketName string // The bucket name.
	objectName string // The object name.
)

// The init function is used to initialize command-line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command-line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Define the content to upload.
	content := "hi oss"

	// Load the default configurations and set the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to upload an object.
	request := &oss.PutObjectRequest{
		Bucket:  oss.Ptr(bucketName),                                                          // The bucket name.
		Key:     oss.Ptr(objectName),                                                          // The object name.
		Body:    strings.NewReader(content),                                                   // The content to upload.
		Expires: oss.Ptr(time.Date(2038, 12, 31, 12, 0, 0, 0, time.UTC).Format(time.RFC1123)), // The expiration time of the object.
		Acl:     oss.ObjectACLPublicRead,
		Metadata: map[string]string{ // Custom metadata.
			"Author": "alibaba oss sdk", // The author of the object.
			"Date":   "2024-07-01",      // The creation date of the object.
		},
	}

	// Send the request to upload the object.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Print the result of the object upload.
	log.Printf("put object result:%#v\n", result)
}

Utiliser ossutil

Utilisez ossutil pour configurer les métadonnées d'objet. Consultez set-meta (gérer les métadonnées d'objet).

Utiliser l'API OSS

Pour appeler directement l'API RESTful OSS, incluez le calcul de signature dans votre code. Pour plus d'informations, consultez PutObject.