Todos os produtos
Search
Central de documentação

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

Última atualização: Jul 03, 2026

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

Observações

  • Este tópico utiliza 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 Regiões e endpoints.

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

Permissões

Por padrão, uma conta Alibaba Cloud tem permissões totais. Usuários RAM ou funções RAM vinculados a essa conta não possuem permissões iniciais. A conta Alibaba Cloud ou o administrador deve conceder as permissões de operação por meio de políticas do RAM ou Bucket Policy.

API

Ação

Descrição

PutObject

oss:PutObject

Faz upload de um objeto.

oss:PutObjectTagging

Necessário se você especificar tags de objeto com o cabeçalho x-oss-tagging durante o upload.

kms:GenerateDataKey

Obrigatório quando o cabeçalho X-Oss-Server-Side-Encryption: KMS estiver definido como KMS no upload do objeto.

kms:Decrypt

Fazer upload de um arquivo da memória

O código a seguir mostra como fazer 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 upload de um arquivo local

O código a seguir mostra como fazer upload do arquivo examplefile.txt do diretório D:\\localpath para o bucket examplebucket. O arquivo é salvo como 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 obter o código de exemplo completo de uploads simples, consulte o GitHub.

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