Todos los productos
Search
Centro de documentos

Object Storage Service:Gestión de metadatos de objetos

Última actualización: Sep 03, 2026

Los metadatos de objetos incluyen encabezados HTTP estándar y metadatos de usuario. Configure los encabezados HTTP para controlar el almacenamiento en caché, el tipo de contenido y el comportamiento de descarga. Agregue metadatos de usuario para etiquetar objetos con pares clave-valor personalizados.

Encabezados HTTP estándar

OSS almacena los siguientes encabezados HTTP estándar para cada objeto cargado.

Encabezado HTTP estándar

Descripción

Content-Type

Tipo de medio del objeto. Los navegadores usan este encabezado para determinar cómo leer el objeto. Si no se especifica, OSS asigna un valor según la extensión del archivo o usa el valor predeterminado application/octet-stream. Para obtener más información, consulte How do I configure the Content-Type header?

Content-Encoding

Método de codificación aplicado al objeto. Establezca este encabezado para que coincida con la codificación real. Si no coinciden, es posible que el navegador no pueda analizar sintácticamente ni descargar el objeto. Déjelo vacío si el objeto no está codificado. Valores válidos:

  • identity (predeterminado): Sin compresión ni codificación.

  • gzip: Codificado con el algoritmo LZ77 y CRC de 32 bits.

  • compress: Codificado con el algoritmo LZW.

  • deflate: Codificado con zlib y el algoritmo deflate.

  • br: Codificado con el algoritmo Brotli.

Content-Encoding se define en RFC 2616.

Importante

Si desea que los objetos de páginas web estáticas, como HTML, JavaScript, XML y JSON, se compriman en formato GZIP al acceder a ellos, deje este encabezado vacío y agregue el encabezado Accept-Encoding: gzip a su solicitud.

Content-Language

Idioma del contenido del objeto. Por ejemplo, establezca este encabezado en zh-CN para contenido en chino simplificado.

Content-Disposition

Controla si el navegador muestra o descarga el objeto. Valores válidos:

  • Content-Disposition:inline: Muestra el objeto en el navegador.

  • Content-Disposition:attachment: Descarga el objeto con su nombre original.

  • Content-Disposition:attachment; filename="yourFileName": Descarga el objeto con un nombre de archivo personalizado.

    yourFileName es el nombre de archivo personalizado, como example.jpg.

Al descargar objetos como archivos adjuntos, considere lo siguiente:

Nota
  • Si el nombre del objeto contiene caracteres especiales como asteriscos () o barras diagonales (/), es posible que el nombre del archivo descargado se escape. Por ejemplo, si descarga example.jpg a su computadora local, example*.jpg podría escaparse como example_.jpg.

  • Para evitar nombres de archivo ilegibles debido a caracteres no ASCII, codifíquelos en URL. Por ejemplo, para descargar el objeto Test.txt con su nombre original Test.txt, establezca el encabezado Content-Disposition en attachment;filename=%E6%B5%8B%E8%AF%95.txt;filename=UTF-8''%E6%B5%8B%E8%AF%95.txt, lo cual se deriva de "attachment;filename="+URLEncoder.encode("Test","UTF-8")+".txt;filename=UTF-8''"+URLEncoder.encode("Test","UTF-8")+".txt".

Que un objeto se previsualice o se descargue como archivo adjunto depende de la hora de creación del bucket, la hora de activación de OSS y el tipo de nombre de dominio. Para obtener más información, consulte What do I do if an image object is downloaded as an attachment but cannot be previewed when I access the image object by using its URL?

Cache-Control

Nota

Si no se establece Cache-Control, OSS omite este campo en el encabezado de respuesta. En consecuencia, el navegador aplica su propia directiva de caché predeterminada.

Controla el comportamiento de almacenamiento en caché del objeto. Valores válidos:

  • no-cache: La caché debe revalidar con el servidor de origen antes de servir el contenido.

  • no-store: No se almacena el objeto en caché.

  • public: Cualquier caché puede almacenar el objeto.

  • private: El objeto se almacena en caché únicamente en el cliente.

  • max-age=<seconds>: Periodo de validez de la caché en segundos. Disponible solo en HTTP 1.1.

Expires

Fecha de caducidad de la caché en formato UTC. Ejemplo: 2022-10-12T00:00:00.000Z. Si se incluye max-age=<seconds> en la configuración del encabezado Cache-Control, max-age=<seconds> tiene prioridad sobre el valor de Expires.

Last-Modified

Hora de la última modificación del objeto, en formato UTC. OSS actualiza automáticamente el encabezado Last-Modified y no se puede cambiar manualmente. Para obtener más información, consulte What are the operations that affect the LastModified attribute of OSS objects?

Nota

La consola de OSS convierte la hora UTC a su zona horaria local. Por ejemplo, un objeto actualizado por última vez a las 13:31:54 UTC del 28 de febrero de 2024 se muestra como 21:31:54 en la zona horaria UTC+8.

Content-Length

Tamaño del objeto. Unidad: bytes.

Metadatos de usuario

Agregue metadatos de usuario al cargar objetos para identificar su propósito o atributos.

  • Un objeto admite varios encabezados de metadatos de usuario, hasta un total de 8 KB.

  • Los encabezados de metadatos de usuario son pares clave-valor. Cada nombre de encabezado debe comenzar con x-oss-meta-. Por ejemplo, x-oss-meta-last-modified:20210506 indica que el archivo local se modificó por última vez el 6 de mayo de 2021.

  • Las operaciones GetObject y HeadObject devuelven los metadatos de usuario como encabezados HTTP.

Procedimiento

Uso de la consola de OSS

La consola de OSS permite configurar metadatos para un máximo de 100 objetos a la vez.

  1. Inicie sesión en la consola de OSS.

  2. En el panel de navegación izquierdo, haga clic en Buckets. En la página que aparece, haga clic en el nombre del bucket de destino.

  3. En el panel de navegación izquierdo, seleccione Object Management > Objects.

  4. Configure los encabezados HTTP estándar y los metadatos de usuario.

    • Configuración de encabezados HTTP para varios objetos simultáneamente

      Seleccione los objetos para los que desea configurar metadatos y haga clic en Set Object Metadata.

    • Configuración de encabezados HTTP para un solo objeto

      Busque el objeto en la lista de objetos y seleccione more > Set Object Metadata.

  5. Haga clic en OK.

  6. OSS no admite la herencia de Cache-Control predeterminado a nivel de bucket. No es posible configurar un valor unificado de Cache-Control para un bucket y hacer que los objetos cargados posteriormente lo hereden automáticamente. Para configurar por lotes el encabezado Cache-Control de objetos existentes, también puede usar ossutil:

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

    Para obtener más información, consulte set-props (configurar propiedades de objetos).

    Common operations in ossbrowser

Uso de ossbrowser

ossbrowser admite las mismas operaciones a nivel de objeto que la consola de OSS. Para obtener más información, consulte 常用操作.

Uso de SDK de OSS

El siguiente código muestra cómo configurar metadatos de objetos con los SDK de OSS. Para SDK en otros lenguajes, consulte 简介.

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)
}

Uso de ossutil

Use ossutil para configurar los metadatos de objetos. Consulte set-meta (manage object metadata).

Uso de la API de OSS

Para llamar directamente a la API RESTful de OSS, incluya el cálculo de firmas en su código. Para obtener más información, consulte PutObject.