Todos os produtos
Search
Central de documentação

Object Storage Service:Download de arquivos com OSS SDK for PHP 2.0

Última atualização: Sep 24, 2026

Este tópico descreve como usar o módulo Downloader do OSS SDK for PHP V2 para baixar arquivos.

Observações

  • O código de exemplo neste tópico usa o endpoint público da região China (Hangzhou) (cn-hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre os mapeamentos de região e endpoint do OSS, consulte Regions and endpoints.

  • Este tópico apresenta um exemplo de obtenção de credenciais de acesso a partir de variáveis de ambiente. Para mais informações, consulte Configure access credentials for PHP.

  • Para baixar um arquivo, é necessário ter a permissão oss:GetObject. Para mais informações, consulte Grant custom permissions to a RAM user.

Definição do método

Introdução ao recurso Downloader

O módulo Downloader do OSS SDK for PHP V2 oferece interfaces de alto nível que simplificam o processo de download de arquivos, abstraindo os detalhes de implementação subjacentes.

  • O módulo Downloader usa download por intervalo para dividir automaticamente um arquivo em múltiplos shards menores para download simultâneo, melhorando o desempenho do download.

  • O módulo Downloader também oferece suporte a download retomável. Durante o download, o status dos shards concluídos é registrado. Se o download falhar por interrupção de rede ou encerramento inesperado do programa, use o arquivo de registro de ponto de retomada para continuar o download a partir do último shard bem-sucedido.

A tabela a seguir descreve os métodos comuns do 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 requisição

Parâmetro

Tipo

Descrição

request

GetObjectRequest

Os parâmetros de requisição para o download do objeto. Os parâmetros são os mesmos da operação GetObject.

filePath

string

O caminho do arquivo local.

args

array

(Opcional) As opções de configuração.

A tabela a seguir descreve os parâmetros comuns em args.

Parâmetro

Tipo

Descrição

part_size

int

O tamanho do shard. O valor padrão é 6 MiB.

parallel_num

int

O número de tarefas de download simultâneas. O valor padrão é 3. Este parâmetro especifica o limite de simultaneidade para uma única chamada, não o limite de simultaneidade global.

use_temp_file

bool

Indica se um arquivo temporário deve ser usado durante o download. Por padrão, um arquivo temporário é utilizado: o arquivo é baixado primeiro para o temporário e, após a conclusão bem-sucedida, o arquivo temporário é renomeado para o arquivo do objeto.

Ao instanciar um Downloader, especifique opções de configuração para personalizar o comportamento do download. Essas opções podem ser aplicadas na criação da instância do Downloader ou em cada chamada de download individualmente.

  • Defina os parâmetros de configuração para a instância do Downloader:

    $d = $client->newDownloader(['part_size' => 10 * 1024 * 1024]);
  • Defina os parâmetros de configuração para cada requisição de download:

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

Código de exemplo

Use o código a seguir para baixar um arquivo de um bucket para sua máquina 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
);

Cenários

Use Downloader to set the shard size and concurrency

Use o código a seguir para definir o tamanho do shard e a simultaneidade do downloader.

<?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
);

Use Downloader to download to a 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.
);

Referências