Todos los productos
Search
Centro de documentos

Object Storage Service:Descarga de archivos con OSS SDK for PHP 2.0

Última actualización: Sep 03, 2026

Este tema describe cómo usar el módulo Downloader en OSS SDK for PHP V2 para descargar archivos.

Notas

  • El código de ejemplo de este tema usa el endpoint público de la región China (Hangzhou) (cn-hangzhou). 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 asignaciones de regiones y endpoints de OSS, consulte Regions and endpoints.

  • Este tema proporciona un ejemplo para obtener credenciales de acceso desde variables de entorno. Para más detalles, consulte Configure access credentials for PHP.

  • Para descargar un archivo, debe contar con el permiso oss:GetObject. Para obtener más información, consulte Grant custom permissions to a RAM user.

Definición de métodos

Introducción a la función Downloader

El módulo Downloader de OSS SDK for PHP V2 ofrece interfaces de alto nivel que simplifican la descarga de archivos al abstraer los detalles de implementación subyacentes.

  • El módulo Downloader usa descargas por rangos para dividir automáticamente un archivo en varios shards más pequeños y descargarlos de forma concurrente, lo cual mejora el rendimiento.

  • El módulo Downloader también admite la descarga reanudable. Durante el proceso, se registra el estado de los shards completados. Si una descarga falla debido a una interrupción de red o a una salida inesperada del programa, use el archivo de registro de puntos de interrupción para reanudarla desde el último shard exitoso.

La siguiente tabla describe los métodos comunes del módulo Downloader.

final class Downloader
{
	...
    public function __construct($client, array $args = [])
    
    public function downloadFile(Models\GetObjectRequest $request, string $filepath, array $args = []): Models\DownloadResult   
    
    public function downloadTo(Models\GetObjectRequest $request, \Psr\Http\Message\StreamInterface $stream, array $args = []): Models\DownloadResult
}

Parámetros de solicitud

Parámetro

Tipo

Descripción

request

GetObjectRequest

Los parámetros de solicitud para la descarga del objeto. Estos parámetros son los mismos que los de la operación GetObject.

filePath

string

La ruta del archivo local.

args

array

(Opcional) Las opciones de configuración.

La siguiente tabla describe los parámetros comunes en args.

Parámetro

Tipo

Descripción

part_size

int

El tamaño del shard. El valor predeterminado es 6 MiB.

parallel_num

int

El número de tareas de descarga simultáneas. El valor predeterminado es 3. Este parámetro especifica el límite de concurrencia para una sola llamada, no el límite global.

use_temp_file

bool

Especifica si se debe usar un archivo temporal durante la descarga. De forma predeterminada, se usa un archivo temporal. El contenido se descarga primero en dicho archivo y, tras completarse la descarga correctamente, se renombra como el archivo de objeto final.

Al crear una instancia de Downloader, especifique opciones de configuración para personalizar el comportamiento de descarga. Estas opciones pueden aplicarse al crear la instancia de Downloader o en cada llamada individual de descarga.

  • Establezca los parámetros de configuración para la instancia de Downloader:

    $d = $client->newDownloader(['part_size' => 10 * 1024 * 1024]);
  • Establezca los parámetros de configuración para cada solicitud de descarga:

    $d->downloadFile(
        new Oss\Models\GetObjectRequest(
            bucket: 'bucket',
            key: 'key'
        ),
        filepath: '/local/dir/example',
        args: ['part_size' => 10 * 1024 * 1024]
    );

Código de ejemplo

Use el siguiente código para descargar un archivo de un bucket a su computadora local.

<?php

// Import the autoload 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. (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 name of the bucket. (Required)
    "key" => ['help' => 'The name of the object', 'required' => True], // The name of the object. (Required)
];

// Convert the argument descriptions to the long option format that is required by getopt.
// Add a colon (:) to the end of each argument to specify that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts);

// Verify that the required arguments exist.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information about 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 name of the bucket.
$key = $options["key"];       // The name of the object.

// 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 downloader instance.
$downloader = $client->newDownloader();

// Define the local file path to save the downloaded content.
$filename = "/Users/yourLocalPath/yourFileName"; // An example of the file path.
touch($filename); // Create an empty file to ensure that the file exists.

// Perform the sharded download operation.
$result = $downloader->downloadFile(
    new Oss\Models\GetObjectRequest(
        bucket: $bucket,
        key: $key
    ),
    $filename
);

// Print the download result.
printf(
    'download status code:' . $result->statusCode . PHP_EOL .
    'download request id:' . $result->requestId . PHP_EOL .
    'download result:' . var_export($result, true) . PHP_EOL
);

Escenarios

Uso de Downloader para configurar el tamaño de shard y la concurrencia

Use el siguiente código para establecer el tamaño de shard y la concurrencia del descargador.

<?php

// Import the autoload 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. (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 name of the bucket. (Required)
    "key" => ['help' => 'The name of the object', 'required' => True], // The name of the object. (Required)
];

// Convert the argument descriptions to the long option format that is required by getopt.
// Add a colon (:) to the end of each argument to specify that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts);

// Verify that the required arguments exist.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information about 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 name of the bucket.
$key = $options["key"];       // The name of the object.

// 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 downloader instance.
$downloader = $client->newDownloader();

// Define the parameters that are related to sharded download.
$partSize = 100 * 1024; // The shard size in bytes. In this example, the shard size is set to 100 KB.

// Define the local file path to save the downloaded content.
$filename = "/Users/yourLocalPath/yourFileName"; // An example of the file path.
touch($filename); // Create an empty file to ensure that the file exists.

// Perform the sharded download operation.
$result = $downloader->downloadFile(
    new Oss\Models\GetObjectRequest(
        bucket: $bucket,
        key: $key
    ),
    $filename,
    args: [ // Optional parameters that are used to customize the sharded download behavior.
        'part_size' => $partSize, // The custom shard size.
        'parallel_num' => 1,      // The number of shards that can be downloaded in parallel.
    ]
);

// Print the download result.
printf(
    'download status code:' . $result->statusCode . PHP_EOL .
    'download request id:' . $result->requestId . PHP_EOL .
    'download result:' . var_export($result, true) . PHP_EOL
);

Uso de Downloader para descargar a un stream

<?php

// Import the autoload 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. (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 name of the bucket. (Required)
    "key" => ['help' => 'The name of the object', 'required' => True], // The name of the object. (Required)
];

// Convert the argument descriptions to the long option format that is required by getopt.
// Add a colon (:) to the end of each argument to specify that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts);

// Verify that the required arguments exist.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information about 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 name of the bucket.
$key = $options["key"];       // The name of the object.

// 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 downloader instance.
$downloader = $client->newDownloader();

// Define a buffer stream to store the downloaded content.
$stream = new \GuzzleHttp\Psr7\BufferStream(1 * 1024 * 1024); // The buffer size is 1 MB.

// Perform the download operation to download the object content to the buffer stream.
$result = $downloader->downloadTo(
    request: new Oss\Models\GetObjectRequest(
        bucket: $bucket,
        key: $key // Specify the name of the object that you want to download.
    ),
    stream: $stream, // Specify the destination stream to store the downloaded content.
);

// Print the downloaded content.
printf(
    'download to body:' . $stream->getContents() . PHP_EOL // Output the content in the buffer stream.
);

Referencias