La función de carga multiparte de OSS permite dividir un objeto grande en varias partes y cargarlas por separado. Una vez cargadas todas las partes, puede llamar a la operación CompleteMultipartUpload para combinarlas en un objeto completo.
Notas
El código de ejemplo de este tema usa la región China (Hangzhou). El ID de la región es
cn-hangzhou. De forma predeterminada, se usa un endpoint público. Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. Para obtener más información sobre las regiones y los endpoints compatibles con OSS, consulte OSS regions and endpoints.Para efectuar una carga multiparte, debe contar con el permiso
oss:PutObject. Para obtener más información, consulte Grant custom access policies to a RAM user.Este tema proporciona un ejemplo de cómo leer las credenciales de acceso desde variables de entorno. Para ver más ejemplos sobre cómo configurar las credenciales de acceso, consulte Configure access credentials for PHP.
Flujo de carga multiparte
Una carga multiparte consta de los siguientes tres pasos:
-
Inicialice un evento de carga multiparte.
Llame al método InitiateMultipartUpload para obtener un ID de carga único global de OSS.
-
Cargue las partes.
Llame al método UploadPart para cargar los datos de cada parte.
NotaSi carga nuevos datos con el mismo número de parte, se sobrescriben los datos existentes de esa parte en OSS.
OSS incluye el hash MD5 de los datos de la parte recibida en el encabezado ETag y le devuelve dicho encabezado.
OSS calcula el hash MD5 de los datos cargados y lo compara con el hash MD5 calculado por el kit de desarrollo de software (SDK). Si ambos hashes MD5 son diferentes, se devuelve el código de error InvalidDigest.
-
Complete la carga multiparte.
Después de cargar todas las partes, llame al método CompleteMultipartUpload para combinar las partes en un archivo completo.
Código de ejemplo
El siguiente código de ejemplo muestra cómo dividir un archivo local grande en varias partes, cargar dichas partes en un bucket y luego combinarlas en un objeto completo.
<?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 that can be used to access OSS. (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 argument descriptions to the long option format required by getopt.
// A colon (:) after each argument indicates that the argument requires a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command-line arguments.
$options = getopt("", $longopts);
// Check whether the required arguments exist.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the help information of the argument.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If a required argument is missing, exit the program.
}
}
// Extract values from the parsed arguments.
$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 credential information 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.
$cfg->setEndpoint('http://oss-cn-hangzhou.aliyuncs.com'); // Set the endpoint.
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Initialize the multipart upload task.
$initResult = $client->initiateMultipartUpload(
new Oss\Models\InitiateMultipartUploadRequest(
bucket: $bucket,
key: $key
)
);
// Define the path of the large file and the part size.
$bigFileName = "/Users/yourLocalPath/yourFileName"; // Specify the path of the large file.
$partSize = 5 * 1024 * 1024; // Set the part size in bytes. In this example, the part size is set to 5 MB.
$fileSize = filesize($bigFileName); // Obtain the file size.
$partsNum = intdiv($fileSize, $partSize) + intval(1); // Calculate the number of parts.
$parts = []; // Used to store the upload result of each part.
$i = 1; // The part number starts from 1.
$file = new \GuzzleHttp\Psr7\LazyOpenStream($bigFileName, 'rb'); // Open the file stream.
while ($i <= $partsNum) {
// Upload a single part.
$partResult = $client->uploadPart(
new Oss\Models\UploadPartRequest(
bucket: $bucket,
key: $key,
partNumber: $i, // The current part number.
uploadId: $initResult->uploadId, // The upload ID returned by the initiated upload task.
contentLength: null, // Optional: The content length of the part.
contentMd5: null, // Optional: The MD5 hash of the part content for validation.
trafficLimit: null, // Optional: The traffic limit.
requestPayer: null, // Optional: The requester pays for the request.
body: new \GuzzleHttp\Psr7\LimitStream($file, $partSize, ($i - 1) * $partSize) // Read the data of the current part.
)
);
// Save the part upload result.
$part = new Oss\Models\UploadPart(
partNumber: $i, // The part number.
etag: $partResult->etag // The ETag value returned after the part is uploaded.
);
array_push($parts, $part); // Save the upload result of the current part to the part list.
$i++; // Increment the part number to process the next part.
}
// Complete the multipart upload task.
$comResult = $client->completeMultipartUpload(
new Oss\Models\CompleteMultipartUploadRequest(
bucket: $bucket,
key: $key,
uploadId: $initResult->uploadId, // The upload ID returned by the initiated upload task.
acl: null, // Optional: Set the access control list (ACL) of the object.
completeMultipartUpload: new Oss\Models\CompleteMultipartUpload(
parts: $parts // Submit the upload results of all parts.
)
)
);
// Print the result of the completed multipart upload.
printf(
'status code:' . $comResult->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful.
'request id:' . $comResult->requestId . PHP_EOL . // The request ID, which is used to debug or track requests.
'complete multipart upload result:' . var_export($comResult, true) . PHP_EOL // The detailed result after the multipart upload is complete.
);
Escenarios comunes
Efectuar una carga multiparte y configurar una devolución de llamada de carga
Referencias
Para consultar el código de ejemplo completo de la carga multiparte, visite Ejemplo en GitHub.