Todos los productos
Search
Centro de documentos

Object Storage Service:Descarga simple (SDK de PHP V2)

Última actualización: Sep 24, 2026

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

Cuando descarga un objeto de un bucket, puede especificar condiciones basadas en la última hora de modificación del objeto o en su ETag. Un ETag es un identificador del contenido del archivo. La operación de descarga se ejecuta únicamente si se cumplen estas condiciones. Si no se cumplen, se devuelve un error y la descarga no se inicia. Las descargas condicionales reducen el tráfico de red innecesario y el consumo de recursos, lo que mejora la eficiencia de la descarga.

A continuación se describen las condiciones que admite OSS.

Nota
  • Puede especificar If-Modified-Since e If-Unmodified-Since en la misma solicitud. También es posible especificar If-Match e If-None-Match en una misma solicitud.

  • Para obtener el ETag, llame al método ossClient.getObjectMeta.

Parámetro

Descripción

IfModifiedSince

Si la hora especificada es anterior a la hora de modificación real del objeto, el objeto se descarga. De lo contrario, se devuelve el error 304 Not Modified.

IfUnmodifiedSince

Si la hora especificada es igual o posterior a la hora de modificación real del objeto, el objeto se descarga. De lo contrario, se devuelve el error 412 Precondition Failed.

IfMatch

Si el ETag especificado coincide con el ETag del objeto de OSS, el objeto se descarga. De lo contrario, se devuelve el error 412 Precondition Failed.

IfNoneMatch

Si el ETag especificado no coincide con el ETag del objeto de OSS, el objeto se descarga. De lo contrario, se devuelve el error 304 Not Modified.

El siguiente código de ejemplo muestra cómo ejecutar una descarga 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.
);

Descarga por streaming

El siguiente código muestra cómo habilitar la descarga por streaming mediante la configuración del parámetro stream al llamar a la operación 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.
}

Mostrar el progreso de la descarga

El siguiente código muestra cómo visualizar el progreso de la descarga al llamar a la operación 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.
);

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.