Todos os produtos
Search
Central de documentação

Object Storage Service:Simple upload (C++ SDK)

Última atualização: Sep 22, 2026

Este tópico descreve como fazer o upload de um arquivo (objeto) a partir da memória ou de um disco local.

Observações

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

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

Permissões

Por padrão, uma conta Alibaba Cloud possui permissões totais. Usuários RAM ou funções RAM vinculados a uma conta Alibaba Cloud não possuem nenhuma permissão por padrão. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões de operação por meio de RAM policies ou Bucket Policy.

API

Ação

Descrição

PutObject

oss:PutObject

Faz o upload de um objeto.

oss:PutObjectTagging

Necessário caso você especifique tags de objeto usando o cabeçalho x-oss-tagging ao fazer o upload de um objeto.

kms:GenerateDataKey

Necessário caso você defina o cabeçalho X-Oss-Server-Side-Encryption: KMS como KMS ao fazer o upload de um objeto.

kms:Decrypt

Fazer o upload de um arquivo a partir da memória

O código a seguir mostra como fazer o upload de conteúdo da memória para o bucket examplebucket. O conteúdo é salvo como o arquivo exampleobject.txt na pasta exampledir.

#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, if the bucket is in 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, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Enter the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Enter the full path of the object. The full path cannot contain the bucket name. For 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);
    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
    *content << "Thank you for using Alibaba Cloud Object Storage Service!";
    PutObjectRequest request(BucketName, ObjectName, content);

    /* (Optional) The following example shows how to set the access control list (ACL) to private and the storage class to Standard. */
    //request.MetaData().addHeader("x-oss-object-acl", "private");
    //request.MetaData().addHeader("x-oss-storage-class", "Standard");

    /* Upload the file. */
    auto outcome = client.PutObject(request);

    if (!outcome.isSuccess()) {
        /* Handle the exception. */
        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;
}

Fazer o upload de um arquivo local

O código a seguir mostra como fazer o upload do arquivo examplefile.txt do diretório D:\\localpath para o bucket examplebucket. O arquivo é salvo como o arquivo exampleobject.txt na pasta exampledir.

#include <alibabacloud/oss/OssClient.h>
#include <fstream>
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, if the bucket is in 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, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Enter the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Enter the full path of the object. The full path cannot contain the bucket name. For 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);
    /* Enter the full path of the local file. For example, D:\\localpath\\examplefile.txt. In this example, localpath is the local directory where the examplefile.txt file is stored. */
    std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>("D:\\localpath\\examplefile.txt", std::ios::in | std::ios::binary);
    PutObjectRequest request(BucketName, ObjectName, content);

    /* (Optional) The following example shows how to set the access control list (ACL) to private and the storage class to Standard. */
    //request.MetaData().addHeader("x-oss-object-acl", "private");
    //request.MetaData().addHeader("x-oss-storage-class", "Standard");

    auto outcome = client.PutObject(request);

    if (!outcome.isSuccess()) {
        /* Handle the exception. */
        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;
}

Referências

  • Para o código de exemplo completo de uploads simples, consulte GitHub.

  • Para mais informações sobre a operação de API para uploads simples, consulte PutObject.