Este tema describe cómo cargar rápidamente archivos locales a Object Storage Service (OSS) mediante la carga simple. Este método es sencillo y adecuado para escenarios en los que se requiere cargar archivos locales de forma rápida.
Notas de uso
El código de ejemplo de este tema utiliza el identificador de región
cn-hangzhou, correspondiente a la región China (Hangzhou). De manera predeterminada, se usa el endpoint público para acceder a los recursos de un bucket. Si desea acceder a los recursos del bucket desde otros servicios de Alibaba Cloud ubicados en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.Para utilizar la carga simple, debe contar con el permiso
oss:PutObject. Para obtener más información, consulte Grant a custom policy.En este tema, las credenciales de acceso se obtienen a partir de variables de entorno. Para obtener más información, consulte Configure access credentials for OSS SDK for PHP.
Código de ejemplo
A continuación se muestra un ejemplo de código para cargar un archivo local a un bucket:
<?php
// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify descriptions for 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 that can be used by other services to access OSS.
"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 the 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']; // Obtain the help information about the parameters.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If the required parameters are not configured, exit the program.
}
}
// Obtain values from the parsed parameters.
$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.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Check whether the local file exists.
if (!file_exists($file)) {
echo "Error: The specified file does not exist." . PHP_EOL; // If the local file does not exist, an error message is displayed and the program is exited.
exit(1);
}
// Open the local file and prepare for the simple upload task.
// Use fopen to open the local file in read-only mode and convert the file to 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; // Specify that the HTTP request body is a file stream.
// Execute the simple upload request.
$result = $client->putObject($request);
// Display the result of the simple upload request.
// Display the HTTP status code, the request ID, and the ETag of the object to check whether the request is successful.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful.
'request id:' . $result-> requestId. PHP_EOL // The request ID, which is used to debug or trace a request.
'etag:' . $result->etag . PHP_EOL // The ETag of the object, which is used to identify the content of the object.
);
Escenarios comunes
Cargar una cadena
Cargar una matriz de bytes
Cargar una secuencia de red
Consultar el progreso de carga de un objeto
Configurar un callback al cargar un archivo local
Referencia
Para consultar el código de ejemplo completo de la carga simple, visite GitHub.