Todos os produtos
Search
Central de documentação

Object Storage Service:Uploader de arquivos (OSS SDK for PHP V2)

Última atualização: Sep 22, 2026

Use o módulo Uploader no OSS SDK for PHP V2 para dividir arquivos grandes em partes, enviá-las em paralelo e retomar transferências interrompidas.

Observações de uso

  • Este 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 o endpoint interno. Para mais informações sobre os mapeamentos entre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Para enviar arquivos, é necessária a permissão oss:PutObject. Para mais informações, consulte Grant a custom policy.

  • Este tópico carrega credenciais de acesso a partir de variáveis de ambiente. Configure access credentials for OSS SDK for PHP.

Métodos

Visão geral do Uploader

O módulo Uploader simplifica o upload de arquivos no OSS SDK for PHP V2.

  • O Uploader divide arquivos grandes ou streams em partes para enviá-las em paralelo.

  • O Uploader suporta uploads retomáveis. Ele registra o status das partes durante a transferência, o que permite retomar o processo a partir de um arquivo de checkpoint após falhas, como interrupções de rede ou encerramentos inesperados, mesmo após várias tentativas.

O Uploader fornece os seguintes métodos:

final class Uploader
{
	...
    public function __construct($client, array $args = [])

    public function uploadFile(Models\PutObjectRequest $request, string $filepath, array $args = []): Models\UploadResult

    public function uploadFrom(Models\PutObjectRequest $request, StreamInterface $stream, array $args = []): Models\UploadResult
	...
}

Parâmetros da requisição

Parâmetro

Tipo

Descrição

request

PutObjectRequest

Parâmetros da requisição de upload, iguais aos do PutObject.

stream

StreamInterface

O stream para envio.

filePath

string

O caminho do arquivo local.

args

array

Parâmetros de configuração opcionais.

Parâmetros comuns de args:

Parâmetro

Tipo

Descrição

part_size

int

Tamanho da parte. Valor padrão: 6 MiB.

parallel_num

int

Número de partes para envio em paralelo. Padrão: 3. Aplica-se por chamada.

leave_parts_on_error

bool

Indica se as partes enviadas são retidas em caso de falha. Padrão: false.

Defina os parâmetros ao criar uma instância do Uploader ou em cada chamada de upload.

  • Defina os parâmetros na instância do Uploader

    $u = $client->newUploader(['part_size' => 10 * 1024 * 1024]);
  • Defina os parâmetros por requisição de upload

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

Código de exemplo

Envie um arquivo local para um bucket:

<?php

// Import autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint for accessing OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) The name of the object.
];

// Construct an array of long options required by getopt.
// Add a colon (:) to the end of each key to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

// Check whether all required arguments are provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the argument help information.
        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 access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to obtain the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if provided. 
}

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

// Specify the path of the local file to be uploaded.
$filename = "/Users/yourLocalPath/yourFileName"; // The sample file path.

// Create an Uploader instance.
$uploader = $client->newUploader();

// Perform the multipart upload operation.
$result = $uploader->uploadFile(
    request: new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key), // Create a PutObjectRequest object to specify the names of the bucket and object.
    filepath: $filename, // Specify the path of the local file to be uploaded.
);

// Display the result of the multipart upload.
printf(
    'multipart upload status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. The status code 200 indicates that the request was successful.
    'multipart upload request id:' . $result->requestId . PHP_EOL .   // The request ID used for debugging or tracking the request.
    'multipart upload result:' . var_export($result, true) . PHP_EOL  // The detailed results of the multipart upload.
);

Cenários comuns

Especifique o tamanho da parte e o paralelismo

Envie um arquivo com tamanho de parte e paralelismo personalizados:

<?php

// Import autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) The name of the object.
];

// Construct an array of long options required by getopt.
// Add a colon (:) to the end of each key to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

// Check whether all required arguments are provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the argument help information.
        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 access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to obtain the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if provided.
}

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

// Configure parameters related to the multipart upload.
$partSize = 100 * 1024; // The part size. Unit: bytes. In this example, the part size is set to 100 KB.

// Specify the path of the local file to be uploaded.
$filename = "/Users/yourLocalPath/yourFileName"; // The sample file path.

// Create an Uploader instance.
$uploader = $client->newUploader();

// Perform the multipart upload operation.
$result = $uploader->uploadFile(
    request: new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key), // Create a PutObjectRequest object to specify the names of the bucket and object.
    filepath: $filename, // Specify the path of the local file to be uploaded.
    args: [ // Optional arguments for customizing multipart upload behaviors.
        'part_size' => $partSize, // Specify a custom part size.
        'parallel_num' => 1, // The number of parts to be uploaded in parallel.
    ]
);

// Display the result of the multipart upload.
printf(
    'multipart upload status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. The status code 200 indicates that the request was successful.
    'multipart upload request id:' . $result->requestId . PHP_EOL .   // The request ID used for debugging or tracking the request.
    'multipart upload result:' . var_export($result, true) . PHP_EOL  // The detailed results of the multipart upload.
);

Envie um stream de arquivo local

Envie um arquivo local como stream:

<?php

// Import autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) The name of the object.
];

// Construct an array of long options 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);

// Check whether all required arguments are provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the argument help information.
        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 access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to obtain the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if provided.
}

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

// Configure parameters related to the multipart upload.
$partSize = 100 * 1024; // The part size. Unit: bytes. In this example, the part size is set to 100 KB.

// Specify the path of the local file to be uploaded.
$filename = "/Users/yourLocalPath/yourFileName"; // The sample file path.

// Create an Uploader instance.
$uploader = $client->newUploader();

// Perform the multipart upload operation.
// Use LazyOpenStream to open the file as a stream to avoid loading the entire file to the memory at a time.
$result = $uploader->uploadFrom(
    request: new Oss\Models\PutObjectRequest(
        bucket: $bucket,
        key: $key
    ),
    stream: new \GuzzleHttp\Psr7\LazyOpenStream($filename, 'rb'), // Open the file stream in read-only mode.
    args: [
        'part_size' => $partSize, // Specify a custom part size.
    ]
);

// Display the result of the multipart upload.
printf(
    'upload from status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. The status code 200 indicates that the request was successful.
    'upload from request id:' . $result->requestId . PHP_EOL .   // The request ID used for debugging or tracking the request.
    'upload from result:' . var_export($result, true) . PHP_EOL  // The detailed results of the multipart upload.
);

Visualize o progresso do upload

Acompanhe o progresso do upload com uma função de callback:

<?php

// Import autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) The name of the object.
];

// Construct an array of long options required by getopt.
// Add a colon (:) to the end of each key to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

// Check whether all required arguments are provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the argument help information.
        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 access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to obtain the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if provided.
}

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

// Configure parameters related to the multipart upload.
$partSize = 100 * 1024; // The part size. Unit: bytes. In this example, the part size is set to 100 KB.

// Specify the path of the local file to be uploaded.
$filename = "/Users/yourLocalPath/yourFileName"; // The sample file path.

// Create an Uploader instance.
$uploader = $client->newUploader();

$request = new \AlibabaCloud\Oss\V2\Models\PutObjectRequest(bucket: $bucket, key: $key);

# Specify the upload progress callback function to display the upload progress.
$request->progressFn = function (int $increment, int $transferred, int $total) {
    echo sprintf("Uploaded: %d" . PHP_EOL, $transferred);
    echo sprintf("This upload: %d" . PHP_EOL, $increment);
    echo sprintf("Total data: %d" . PHP_EOL, $total);
    echo '-------------------------------------------' . PHP_EOL;
};

// Perform the multipart upload operation.
$result = $uploader->uploadFile(request: $request,filepath: $filename);

// Display the result of the multipart upload.
printf(
    'multipart upload status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. The status code 200 indicates that the request was successful,
    'multipart upload request id:' . $result->requestId . PHP_EOL .   // The request ID used for debugging or tracking the request.
    'multipart upload result:' . var_export($result, true) . PHP_EOL  // The detailed results of the multipart upload.
);

Envie um arquivo com callback de upload configurado

Envie um arquivo e notifique o servidor da sua aplicação via callback:

<?php

// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region where the bucket is located
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint for accessing OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) The name of the object.
];

// Construct an array of long options required by getopt.
// Add a colon (:) to the end of each key to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

// Check whether all required arguments are provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the argument help information.
        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 access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to obtain the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if provided. 
}

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

// Configure parameters related to the multipart upload.
$partSize = 100 * 1024; // The part size. Unit: bytes. In this example, the part size is set to 100 KB.

// Specify the path of the local file to be uploaded.
$filename = "/Users/yourLocalPath/yourFileName"; // Replace the value with your actual file path.

// Create an Uploader instance.
$uploader = $client->newUploader();

// ADD x-oss-callback AND x-oss-callback-var headers.
// Define the callback URL.
 $call_back_url = "http://www.example.com/callback";

// Define callback settings: Base64-encoded callback URL and callback body.
// Replace ${x:var1} and ${x:var2} with {var1} and {var2}, respectively.
$callback_body_template = "bucket={bucket}&object={object}&my_var_1={var1}&my_var_2={var2}";
$callback_body_replaced = str_replace(
    ['{bucket}', '{object}', '{var1}', '{var2}'],
    [$bucket, $key, 'value1', 'value2'],
    $callback_body_template
);
$callback = base64_encode(json_encode([
    "callbackUrl" => $call_back_url,
    "callbackBody" => $callback_body_replaced
]));

// Construct callback-var that is Base64-encoded.
$callback_var = base64_encode(json_encode([
    "x:var1" => "value1",
    "x:var2" => "value2"
]));

// Perform the multipart upload
$result = $uploader->uploadFile(
    request: new Oss\Models\PutObjectRequest(
                    bucket: $bucket,
                    key: $key,
                    callback: $callback,
                    callbackVar: $callback_var,), // Create a PutObjectRequest object to specify the names of the bucket and object.
    filepath: $filename, // Specify the path of the local file to be uploaded.
);

// Display the result of the multipart upload.
printf(
    'multipart upload status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. The status code 200 indicates that the request was successful.
    'multipart upload request id:' . $result->requestId . PHP_EOL .   // The request ID used for debugging or tracking the request.
    'multipart upload result:' . var_export($result, true) . PHP_EOL  // The detailed results of the multipart upload.
);

Referências