Este tema describe cómo usar el método de descarga simple para descargar un objeto de un bucket a un archivo local. Este método es directo y adecuado para descargar objetos de OSS a su computadora local de forma rápida.
Precauciones
El código de ejemplo de este tema usa la región China (Hangzhou) (ID de región:
cn-hangzhou) como ejemplo. De manera predeterminada, se usa un endpoint de Internet. Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. Para obtener más información sobre las regiones y los endpoints que admite OSS, consulte OSS regions and endpoints.Para descargar un objeto a un archivo local, debe contar con el permiso
oss:GetObject. Para obtener más información, consulte Grant custom access policies to RAM users.Este tema incluye un ejemplo sobre cómo obtener credenciales de acceso desde variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials for PHP.
Código de ejemplo
Use el siguiente código para descargar un objeto de un bucket a un archivo 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.
);
Escenarios
Descarga condicional
Descarga por streaming
Mostrar el progreso de la descarga
Referencias
Para consultar el código de ejemplo completo que se utiliza para descargar un objeto a un archivo local, vea el ejemplo en GitHub.