This topic describes how to quickly upload local files to Object Storage Service (OSS) using simple upload. This method is straightforward and suitable for scenarios where you need to quickly upload local files.
Considerations
In this topic, the region ID
cn-hangzhou
of China (Hangzhou) is used as an example. By default, the public endpoint is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use the internal endpoint. For more information about the mapping between regions and endpoints supported by OSS, see OSS regions and endpoints.To perform simple upload, you must have the
oss:PutObject
permission. For more information, see Grant custom permissions to a Resource Access Management (RAM) user.In this topic, access credentials obtained from environment variables are used. For more examples of how to configure access credentials, see Configure access credentials for PHP.
Sample code
The following sample code demonstrates how to upload a local file to a bucket:
<?php
// Include the autoload file so that the required dependencies can be loaded
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define and describe command-line parameters
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
"key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
"file" => ['help' => 'Local path to the file you want to upload.', 'required' => True], // (Required) Specify the path of the local file.
];
// Convert the parameter descriptions to a long options list required by getopt
// Add a colon (:) to the end of each parameter to indicate that a value is required
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse command line parameters
$options = getopt("", $longopts);
// Check whether the required parameters are configured
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Get the help information for the parameter
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // Exit the program if a required parameter is missing
}
}
// Extract parsed arguments and use them
$region = $options["region"]; // The region in which the bucket is located
$bucket = $options["bucket"]; // The name of the bucket
$key = $options["key"]; // The name of the object
$file = $options["file"]; // The path of the local file
// Obtain access credentials from environment variables
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey 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 credentials provider
$cfg->setRegion($region); // Set the region in which the bucket is located
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint
}
// Create an OSSClient instance
$client = new Oss\Client($cfg);
// Check whether the file exists
if (!file_exists($file)) {
echo "Error: The specified file does not exist." . PHP_EOL; // If the file does not exist, print an error message and exit
exit(1);
}
// Open the local file and prepare for the upload
// Use fopen to open the local file in read-only mode and convert the file content into a stream by using Utils::streamFor
$body = Oss\Utils::streamFor(fopen($file, 'r'));
// Create a PutObjectRequest object to upload the local file
$request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key);
$request->body = $body; // Set the request body to the file stream
// Perform the upload operation
$result = $client->putObject($request);
// Display the result of the simple upload request
// Display the HTTP status code, request ID, and ETag, to check whether the request is successful
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code, such as 200, which indicates that the request is successful
'request id:' . $result->requestId . PHP_EOL . // The request ID, which is used to debug or track the request
'etag:' . $result->etag . PHP_EOL // The ETag of the object, which is used to identify the uniqueness of the object
);
Scenarios
References
For the complete sample code for simple upload, see GitHub.