Todos os produtos
Search
Central de documentação

Object Storage Service:Manage object metadata (C++ SDK)

Última atualização: Sep 22, 2026

Os objetos armazenados no Object Storage Service (OSS) consistem em chaves, dados e metadados. Os metadados descrevem o objeto e incluem cabeçalhos HTTP padrão e metadados de usuário. Configurar cabeçalhos HTTP padrão permite criar políticas personalizadas de requisição HTTP, como políticas de cache e de download forçado de objetos. Além disso, você pode configurar metadados de usuário para identificar as finalidades ou os atributos do objeto.

Observações

  • Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Este tópico demonstra como criar uma instância do OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Create an OssClient instance.

  • Para definir metadados de objeto, você deve ter a permissão oss:PutObject. Para consultar metadados de objeto, você deve ter a permissão oss:GetObject. Para saber mais, consulte Grant a custom policy.

Defina metadados de objetos

O código a seguir mostra como definir metadados de objeto.

#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;
}

Obtenha metadados de objetos

Recupere metadados de objeto usando um dos seguintes métodos:

Método

Descrição

Benefício

GetObjectMeta

Obtém o ETag, o tamanho e a hora da última modificação de um objeto.

Mais leve e rápido

HeadObject

Obtém todos os metadados de um objeto.

Nenhum

O código a seguir fornece um exemplo de como consultar metadados de objeto:

#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);

    /* Get partial metadata of the object. */
    auto outcome = client.GetObjectMeta(BucketName, ObjectName);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "GetObjectMeta fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }
    else { 
        auto metadata = outcome.result();
        std::cout << " get metadata success, ETag:" << metadata.ETag() << "; LastModified:" 
        << metadata.LastModified() << "; Size:" << metadata.ContentLength() << std::endl;
    }

    /* Get all metadata of the object. */
    outcome = client.HeadObject(BucketName, ObjectName);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "HeadObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }
    else { 
        auto headMeta = outcome.result();
        std::cout <<"headMeta success, ContentType:" 
        << headMeta.ContentType() << "; ContentLength:" << headMeta.ContentLength() 
        << "; CacheControl:" << headMeta.CacheControl() << std::endl;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Referências

  • Para ver o código de exemplo completo que mostra como definir e recuperar metadados de objeto, consulte o GitHub.

  • Para obter detalhes sobre a operação de API que você pode chamar para definir metadados de objeto durante um upload simples, consulte PutObject.

  • Para saber mais sobre as operações de API que você pode chamar para consultar metadados de objeto, consulte GetObjectMeta e HeadObject.