Este tópico descreve como usar o método de download por intervalo para recuperar eficientemente uma parte específica de um objeto.
Pré-requisitos
O código de exemplo neste tópico usa o endpoint público da região China (Hangzhou) (
cn-hangzhou) como exemplo. Se você acessar o OSS a partir de outro service do Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre os mapeamentos entre regiões e endpoints compatíveis com o OSS, consulte Regions and endpoints.Para usar o download por intervalo, é necessário ter a permissão
oss:GetObject. Para obter mais informações, consulte Grant custom access policies to RAM users.
-
Considere um objeto de 1.000 bytes. O intervalo de download válido vai de 0 a 999. Se o intervalo especificado for inválido, o cabeçalho Range não terá efeito. O sistema retorna um código de status 200 OK e transfere o objeto inteiro. A seguir, confira exemplos de solicitações inválidas e suas respectivas respostas:
Ao especificar
Range: bytes=500-2000, o fim do intervalo é inválido. O sistema retorna o objeto inteiro com o código de status HTTP 200.Ao especificar
Range: bytes=1000-2000, o início do intervalo é inválido. O sistema retorna o objeto inteiro com o código de status HTTP 200.
-
Adicione o cabeçalho de solicitação x-oss-range-behavior:standard para alterar o comportamento de download do OSS ao especificar um intervalo inválido. Considere um objeto de 1.000 bytes:
Ao especificar
Range: bytes=500-2000, o fim do intervalo é inválido. O sistema retorna o conteúdo no intervalo de 500 a 999 bytes com o código de status HTTP 206.Ao especificar
Range: bytes=1000-2000, o início do intervalo é inválido. O sistema retorna o código de status HTTP 416 e o código de erro InvalidRange.
Código de exemplo
O código de exemplo a seguir mostra como baixar dados de um intervalo especificado de um objeto ao adicionar o cabeçalho de solicitação RangeBehavior:standard.
<?php
// Import the autoloader file to ensure that dependency libraries are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the description of command line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. This parameter is optional.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name. This parameter is required.
"key" => ['help' => 'The name of the object', 'required' => True], // The object name. This parameter is required.
];
// Convert the argument descriptions to the long option format required by getopt.
// A colon (:) after each argument indicates that the argument requires a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line arguments.
$options = getopt("", $longopts);
// Verify that all required arguments are specified.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the help information for the argument.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If a required argument is missing, exit the program.
}
}
// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"]; // The object name.
// Load the credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Specify the standard download behavior. In this example, the value is set to 'standard'.
$rangeBehavior = 'standard';
// Specify the Range request header to retrieve a part of the object.
$rangeHeader = 'bytes=0-10';
// Create a GetObjectRequest object to retrieve the content of the specified object.
$request = new Oss\Models\GetObjectRequest(
bucket: $bucket,
key: $key,
rangeBehavior: $rangeBehavior,
rangeHeader: $rangeHeader);
// Execute the GetObject operation.
$result = $client->getObject($request);
// Print the result.
// Output the HTTP status code, request ID, and object content.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful.
'request id:' . $result->requestId . PHP_EOL . // The request ID, which is used for debugging or request tracking.
'object content:' . $result->body->getContents() . PHP_EOL // The object content.
);