Se você precisar apenas de uma parte dos dados de um arquivo, use o download por intervalo para recuperar um intervalo específico de dados.
Observações
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros services da Alibaba Cloud na mesma região do OSS, use um endpoint interno. Para obter mais informações sobre as regiões e endpoints do OSS, consulte Regions and endpoints.
Crie uma instância do OSSClient com um endpoint do OSS, conforme demonstrado neste tópico. Para configurações alternativas, como o uso de um domínio personalizado ou a autenticação com credenciais do Security Token Service (STS), consulte Create an OssClient instance.
Para baixar dados por intervalo, você deve ter a permissão
oss:GetObject. Para mais informações, consulte Grant a custom policy.
Especifique um intervalo de download normal
Especifique um intervalo válido para baixar dados conforme o código de exemplo a seguir:
#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, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com for a bucket in the China (Hangzhou) region. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, set the region to cn-hangzhou for a bucket in the China (Hangzhou) region. */
std::string Region = "yourRegion";
/* Specify the bucket name. For example, examplebucket. */
std::string BucketName = "examplebucket";
/* Specify 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);
/* Get the file. */
GetObjectRequest request(BucketName, ObjectName);
/* Set the download range. */
request.setRange(0, 1);
auto outcome = client.GetObject(request);
if (!outcome.isSuccess ()) {
/* Handle the exception. */
std::cout << "getObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
Especifique um intervalo inválido para baixar dados
Para um objeto com tamanho de 1.000 bytes, o intervalo válido vai do byte 0 ao byte 999. Se o intervalo especificado não estiver entre o byte 0 e o byte 999, ele não terá efeito. Nesse caso, o OSS retorna o código de status HTTP 200 e os dados de todo o objeto. Os exemplos a seguir mostram requisições inválidas e os resultados retornados:
Defina Range: bytes como 500-2000. Como o valor no final do intervalo é inválido, o OSS retorna o código de status HTTP 200 e os dados de todo o objeto.
Defina Range: bytes como 1000-2000. Como o valor no início do intervalo é inválido, o OSS retorna o código de status HTTP 200 e os dados de todo o objeto.
Comportamento padrão para downloads por intervalo
Ao adicionar x-oss-range-behavior:standard ao cabeçalho da requisição, o comportamento de download é modificado quando o intervalo especificado não está dentro do intervalo válido. Para um objeto com tamanho de 1.000 bytes:
Defina Range: bytes como 500-2000. Como o valor no final do intervalo é inválido, o OSS retorna o código de status HTTP 206 e os dados que estão dentro do intervalo do byte 500 ao byte 999.
Defina Range: bytes como 1000-2000. Como o valor no início do intervalo é inválido, o OSS retorna o código de status HTTP 416 e o código de erro InvalidRange.
Especifique comportamentos padrão para baixar dados por intervalo conforme o código de exemplo a seguir:
#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, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com for a bucket in the China (Hangzhou) region. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, set the region to cn-hangzhou for a bucket in the China (Hangzhou) region. */
std::string Region = "yourRegion";
/* Specify the bucket name. For example, examplebucket. */
std::string BucketName = "examplebucket";
/* Specify a file that is 1000 bytes in size. */
/* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/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 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 the file. */
GetObjectRequest request(BucketName, ObjectName);
/* Set the download range. */
/* The end of the range is outside the valid interval. The content from byte 500 to 999 is returned, and the HTTP status code is 206. */
request.setRange(500, 2000, true);
auto outcome = client.GetObject(request);
/* The start of the range is outside the valid interval. An exception is thrown. The HTTP status code 416 is returned with the InvalidRange error code. */
request.setRange(1000, 2000, true);
outcome = client.GetObject(request);
if (!outcome.isSuccess ()) {
/* Handle the exception. */
std::cout << "getObject 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 mais informações sobre a operação da API para downloads por intervalo, consulte GetObject.