Este tópico descreve como baixar um objeto do Object Storage Service (OSS) para a memória.
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.
O exemplo demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Crie 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 têm permissões por padrão. A conta Alibaba Cloud ou o administrador deve conceder as permissões operacionais necessárias por meio de políticas do RAM ou Bucket Policy.
|
API |
Ação |
Descrição |
|
GetObject |
|
Baixa um objeto. |
|
|
Necessária ao especificar a versão do objeto via versionId durante o download. |
|
|
|
Necessária se os metadados do objeto contiverem X-Oss-Server-Side-Encryption: KMS durante o download. |
Código de exemplo
O código a seguir mostra como baixar um objeto específico do OSS para a memória:
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the 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";
/* Specify the bucket name. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. The path cannot contain the bucket name. Example: desrfolder/exampleobject.txt. */
std::string ObjectName = "yourObjectName";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 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. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Download the object to memory. */
GetObjectRequest request(BucketName, ObjectName);
auto outcome = client.GetObject(request);
if (outcome.isSuccess()) {
std::cout << "getObjectToBuffer" << " success, Content-Length:" << outcome.result().Metadata().ContentLength() << std::endl;
/* Read data using the read interface. */
auto& stream = outcome.result().Content();
char buffer[256];
while (stream->good()) {
stream->read(buffer, 256);
auto count = stream->gcount();
/* Process the data as needed. */
}
}
else {
/* Handle the exception. */
std::cout << "getObjectToBuffer fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}