Todos os produtos
Search
Central de documentação

Object Storage Service:Download simples (PHP SDK V2)

Última atualização: Sep 24, 2026

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

Ao baixar um objeto de um bucket, é possível especificar condições com base no horário da última modificação do objeto ou no ETag. O ETag é um identificador do conteúdo do arquivo. O download só é executado quando essas condições são atendidas. Caso contrário, um erro é retornado e o download não é iniciado. Downloads condicionais reduzem o tráfego de rede desnecessário e o consumo de recursos, melhorando a eficiência do download.

A tabela a seguir descreve as condições compatíveis com o OSS.

Nota
  • É possível especificar If-Modified-Since e If-Unmodified-Since na mesma requisição. Também é possível especificar If-Match e If-None-Match na mesma requisição.

  • Chame o método ossClient.getObjectMeta para obter o ETag.

Parâmetro

Descrição

IfModifiedSince

Se o horário especificado for anterior ao horário real de modificação do objeto, o objeto é baixado. Caso contrário, o erro 304 Not Modified é retornado.

IfUnmodifiedSince

Se o horário especificado for igual ou posterior ao horário real de modificação do objeto, o objeto é baixado. Caso contrário, o erro 412 Precondition Failed é retornado.

IfMatch

Se o ETag especificado corresponder ao ETag do objeto no OSS, o objeto é baixado. Caso contrário, o erro 412 Precondition Failed é retornado.

IfNoneMatch

Se o ETag especificado não corresponder ao ETag do objeto no OSS, o objeto é baixado. Caso contrário, o erro 304 Not Modified é retornado.

O código de exemplo a seguir mostra como executar um download condicional.

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

// Assume that the last modified time of the object is 18:43:02 on October 21, 2024. If the specified UTC time is earlier than this time, the IfModifiedSince condition is met and the download is triggered.
$ifModifiedSince = "Sun, 21 Oct 2024 18:43:02 GMT";

// Assume that the ETag is e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855. If the specified ETag is the same as the ETag of the object, the IfMatch condition is met and the download is triggered.
$etag = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

// Create a GetObjectRequest object to obtain the content of the specified object.
$request = new Oss\Models\GetObjectRequest(
            bucket: $bucket,
            key: $key,
            ifModifiedSince: $ifModifiedSince,
            ifMatch: $etag);

// Execute the get object 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 tracking requests.
    'object content:' . $result->body->getContents() . PHP_EOL // The object content.
);

Download em streaming

O código a seguir mostra como ativar o download em streaming definindo o parâmetro stream ao chamar a operação GetObject.

<?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";
        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.

// Use EnvironmentVariableCredentialsProvider to load access credentials from environment variables.
// Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are correctly set.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load 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 the endpoint parameter is provided in the command line, use the specified endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a GetObjectRequest object and specify the bucket and object key.
$request = new Oss\Models\GetObjectRequest(bucket: $bucket, key: $key);

// Call the getObject method to download the object. Set the stream option to true to process large files in a stream.
$result = $client->getObject(request: $request, args: ['request_options' => ['stream' => true]]);

// Obtain the stream object.
$stream = $result->body;

// Read the stream content (in chunks).
while (!$stream->eof()) { // Check whether the stream has ended.
    echo $stream->read(1024); // Read 1 KB of data at a time and output the data.
}

Exibir o progresso do download

O código a seguir mostra como exibir o progresso do download ao chamar a operação GetObject.

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

# Set the progress callback function to display the download progress information.
$request->progressFn = static function (int $increment, int $transferred, int $total) {
    echo sprintf("Downloaded: %d" . PHP_EOL, $transferred);
    echo sprintf("Current download: %d" . PHP_EOL, $increment);
    echo sprintf("Total data: %d" . PHP_EOL, $total);
    echo '-------------------------------------------' . PHP_EOL;
};

// Execute the get object 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 tracking requests.
    'object content:' . $result->body->getContents() . PHP_EOL // The object content.
);

Referências

  • Para o código de exemplo completo utilizado para baixar um objeto para um arquivo local, consulte o exemplo no GitHub.