Este tópico descreve como fazer upload rápido de arquivos locais para o Object Storage Service (OSS) por meio do upload simples. Esse método é direto e adequado para cenários que exigem transferência ágil de arquivos locais.
Observações de uso
O código de exemplo deste tópico usa o ID da região
cn-hangzhou, referente à região China (Hangzhou). Por padrão, o acesso aos recursos de um bucket ocorre via endpoint público. Para acessar esses recursos por meio de outros serviços da Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.Para usar o upload simples, você precisa da permissão
oss:PutObject. Para saber mais, consulte Conceder uma política personalizada.Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para mais informações, consulte Configurar credenciais de acesso para o OSS SDK for PHP.
Código de exemplo
O código a seguir demonstra como enviar um arquivo local para um 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.
);
Cenários comuns
Fazer upload de uma string
Fazer upload de um array de bytes
Fazer upload de um fluxo de rede
Consultar o progresso do upload de um objeto
Configurar um callback ao fazer upload de um arquivo local
Referência
Para obter o código completo de exemplo sobre upload simples, visite o GitHub.