All Products
Search
Document Center

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

Last Updated:Aug 05, 2025

This topic describes how to use the Uploader module in the Object Storage Service (OSS) SDK for PHP V2 to upload files.

Usage notes

  • This topic uses the public endpoint of the China (Hangzhou) region (cn-hangzhou) as an example. If you access OSS from other Alibaba Cloud services in the same region, use the internal endpoint. For more information about OSS region and endpoint mappings, see Regions and endpoints.

  • To upload files, you must have the oss:PutObject permission. For more information, see Attach a custom policy to a RAM user.

  • This topic uses environment variables to obtain access credentials. For more information about how to configure access credentials, see Configure access credentials for OSS SDK for PHP.

Method definition

Uploader overview

The Uploader module of the OSS SDK for PHP V2 provides common API operations to simplify file uploads.

  • The Uploader module uses multipart upload operations to split a large file or stream into multiple parts for parallel uploads. This improves upload performance.

  • The Uploader module also provides resumable upload capabilities. During an upload, the status of uploaded parts is recorded. If an upload fails due to issues such as a network interruption or an unexpected program exit, you can resume the upload from the recorded breakpoint.

The Uploader module has the following common methods:

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
	...
}

Request parameters

Parameter

Type

Description

request

PutObjectRequest

The request parameters for the object upload. The parameters are the same as those of the PutObject operation.

stream

StreamInterface

The stream to be uploaded.

filePath

string

The path of the local file.

args

array

(Optional) The configuration options.

The following table describes common parameters in args.

Parameter

Type

Description

part_size

int

The part size. The default value is 6 MiB.

parallel_num

int

The number of concurrent upload tasks. The default value is 3. This parameter specifies the concurrency limit for a single call, not the global concurrency limit.

leave_parts_on_error

bool

Specifies whether to retain uploaded parts when the upload fails. By default, uploaded parts are not retained.

When you use newUploader to instantiate an Uploader instance, you can specify configuration options to customize the upload behavior. You can also specify configuration options for each upload operation to customize the behavior for a specific object.

  • Set the configuration parameters for the Uploader

    $u = $client->newUploader(['part_size' => 10 * 1024 * 1024]);
  • Set the configuration parameters for each upload request

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

Sample code

The following sample code shows how to use the uploader to upload a local file to a bucket.

<?php

// Import the autoloader file to ensure that dependency libraries can be loaded correctly.
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 parameter descriptions to the long option format required by getopt.
// Add a colon ":" after each parameter to indicate that the parameter requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Load the access credential 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);

// Define the path of the local file to upload.
$filename = "/Users/yourLocalPath/yourFileName"; // An example file path.

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

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

// Print the multipart upload result.
printf(
    'multipart upload status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates success.
    'multipart upload request id:' . $result->requestId . PHP_EOL .   // The request ID, which is used to debug or track the request.
    'multipart upload result:' . var_export($result, true) . PHP_EOL  // The detailed result of the multipart upload.
);

Scenarios

Use the uploader to set the part size and concurrency

The following sample code shows how to set configuration parameters for the Uploader, such as the part size and concurrency.

<?php

// Import the autoloader file to ensure that dependency libraries can be loaded correctly.
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 parameter descriptions to the long option format required by getopt.
// Add a colon ":" after each parameter to indicate that the parameter requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Load the access credential 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);

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

// Define the path of the local file to upload.
$filename = "/Users/yourLocalPath/yourFileName"; // An example file path.

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

// Execute the multipart upload operation.
$result = $uploader->uploadFile(
    request: new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key), // Create a PutObjectRequest object and specify the bucket and object names.
    filepath: $filename, // Specify the path of the local file to upload.
    args: [ // Optional parameters used to customize the multipart upload behavior.
        'part_size' => $partSize, // A custom part size.
        'parallel_num' => 1, // The number of parts to upload concurrently.
    ]
);

// Print the multipart upload result.
printf(
    'multipart upload status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates success.
    'multipart upload request id:' . $result->requestId . PHP_EOL .   // The request ID, which is used to debug or track the request.
    'multipart upload result:' . var_export($result, true) . PHP_EOL  // The detailed result of the multipart upload.
);

Use the uploader to upload a local file stream

The following sample code shows how to use the uploader to upload a local file stream.

<?php

// Import the autoloader file to ensure that dependency libraries can be loaded correctly.
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 parameter descriptions to the long option format required by getopt.
// Add a colon ":" after each parameter to indicate that the parameter requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Load the access credential 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);

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

// Define the path of the local file to upload.
$filename = "/Users/yourLocalPath/yourFileName"; // An example file path.

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

// Execute the multipart upload operation.
// Use LazyOpenStream to open the file as a stream to prevent the entire file from being loaded into 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, // A custom part size.
    ]
);

// Print the upload result.
printf(
    'upload from status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates success.
    'upload from request id:' . $result->requestId . PHP_EOL .   // The request ID, which is used to debug or track the request.
    'upload from result:' . var_export($result, true) . PHP_EOL  // The detailed result of the upload.
);

Use the uploader to display the upload progress

The following sample code shows how to display the upload progress when you use the uploader to upload a local file.

<?php

// Import the autoloader file to ensure that dependency libraries can be loaded correctly.
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 parameter descriptions to the long option format required by getopt.
// Add a colon ":" after each parameter to indicate that the parameter requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Load the access credential 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);

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

// Define the path of the local file to upload.
$filename = "/Users/yourLocalPath/yourFileName"; // An example file path.

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

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

# Set 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;
};

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

// Print the multipart upload result.
printf(
    'multipart upload status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates success.
    'multipart upload request id:' . $result->requestId . PHP_EOL .   // The request ID, which is used to debug or track the request.
    'multipart upload result:' . var_export($result, true) . PHP_EOL  // The detailed result of the multipart upload.
);

Use the uploader to set an upload callback

If you want to notify the application server after a file is uploaded, use the following sample code.

<?php

// Import the autoloader file to ensure that dependency libraries can be loaded correctly.
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 parameter descriptions to the long option format required by getopt.
// Add a colon ":" after each parameter to indicate that the parameter requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Load the access credential 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);

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

// Define the path of the local file to upload.
$filename = "/Users/yourLocalPath/yourFileName"; // An example file path.

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

// Add the x-oss-callback and x-oss-callback-var headers.
// Define the webhook address.
 $call_back_url = "http://www.example.com/callback";

// Construct the callback parameter (callback): specify the webhook address and request body, and use Base64 encoding.
// Use the placeholders {var1} and {var2} to replace ${x:var1} and ${x:var2}.
$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 the custom variable (callback-var) and use Base64 encoding.
$callback_var = base64_encode(json_encode([
    "x:var1" => "value1",
    "x:var2" => "value2"
]));

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

// Print the multipart upload result.
printf(
    'multipart upload status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates success.
    'multipart upload request id:' . $result->requestId . PHP_EOL .   // The request ID, which is used to debug or track the request.
    'multipart upload result:' . var_export($result, true) . PHP_EOL  // The detailed result of the multipart upload.
);

References