Este tópico descreve como usar o método de download simples para baixar um objeto de um bucket para um arquivo local. O método é direto e adequado para baixar objetos do OSS rapidamente para o computador local.
Precauções
O código de exemplo neste tópico usa a região China (Hangzhou) (Region ID:
cn-hangzhou) como referência. Por padrão, um endpoint de Internet é utilizado. 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 as regiões e endpoints compatíveis com o OSS, consulte OSS regions and endpoints.Para baixar um objeto para um arquivo local, é necessário ter a permissão
oss:GetObject. Para obter mais informações, consulte Grant custom access policies to RAM users.Este tópico apresenta um exemplo de como obter credenciais de acesso a partir de variáveis de ambiente. Para obter mais informações sobre como configurar credenciais de acesso, consulte Configure access credentials for PHP.
Código de exemplo
Use o código a seguir para baixar um objeto de um bucket para um arquivo local.
<?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 parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. (Required)
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. (Optional)
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name. (Required)
"key" => ['help' => 'The name of the object', 'required' => True], // The object name. (Required)
];
// Convert the parameter description to the long option format required by getopt.
// A colon ":" after each parameter indicates that the parameter requires a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters exist.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the help information of the parameter.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If a required parameter is missing, exit the program.
}
}
// Extract values from the parsed parameters.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"]; // The object name.
// Load the credential information 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 credential 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);
// Create a GetObjectRequest object to obtain the content of the specified object.
$request = new Oss\Models\GetObjectRequest(bucket: $bucket, key: $key);
// Execute the get object operation.
$result = $client->getObject($request);
// Define the path of the local file to be saved.
$localFilePath = 'path/to/local/file.txt'; // Replace it with the actual file path.
// Write the content to the local file.
file_put_contents( $localFilePath, $result->body->getContents());
// 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 tracking requests.
);
Cenários
Download condicional
Download em streaming
Exibir o progresso do download
Referências
Para o código de exemplo completo utilizado para baixar um objeto para um arquivo local, consulte o exemplo no GitHub.