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:PutObjectpermission. 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
References
For more information about the uploader, see Developer Guide.
For the complete sample code of the uploader, see GitHub Example.