La fonctionnalité de téléchargement multipartie d'OSS vous permet de diviser un objet volumineux en plusieurs parties et de les télécharger séparément. Une fois toutes les parties téléchargées, vous pouvez appeler l'opération CompleteMultipartUpload pour combiner ces parties en un objet complet.
Notes
L'exemple de code présenté dans cette rubrique utilise la région Chine (Hangzhou). L'ID de région est
cn-hangzhou. Par défaut, un endpoint public est utilisé. Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints pris en charge par OSS, reportez-vous à Régions et endpoints OSS.Pour effectuer un téléchargement multipartie, vous devez disposer de l'autorisation
oss:PutObject. Pour plus d'informations, consultez la rubrique Accorder des politiques d'accès personnalisées à un utilisateur RAM.Cette rubrique fournit un exemple montrant comment lire les informations d'identification d'accès à partir des variables d'environnement. Pour d'autres exemples de configuration des informations d'identification d'accès, reportez-vous à la section Configurer les informations d'identification d'accès pour PHP.
Flux de téléchargement multipartie
Un téléchargement multipartie se déroule en trois étapes :
-
Initialisez une opération de téléchargement multipartie.
Appelez la méthode InitiateMultipartUpload pour obtenir un ID de téléchargement globalement unique auprès d'OSS.
-
Téléchargez les parties.
Appelez la méthode UploadPart pour télécharger les données de chaque partie.
RemarqueSi vous téléchargez de nouvelles données avec le même numéro de partie, les données existantes de cette partie dans OSS sont écrasées.
OSS inclut le hachage MD5 des données de la partie reçues dans l'en-tête ETag et vous renvoie cet en-tête.
OSS calcule le hachage MD5 des données téléchargées et le compare au hachage MD5 calculé par le kit de développement logiciel (SDK). Si les deux hachages MD5 diffèrent, le code d'erreur InvalidDigest est renvoyé.
-
Finalisez le téléchargement multipartie.
Une fois toutes les parties téléchargées, appelez la méthode CompleteMultipartUpload pour combiner les parties en un fichier complet.
Exemple de code
L'exemple de code suivant montre comment diviser un fichier local volumineux en plusieurs parties, télécharger ces parties dans un bucket, puis les combiner pour former un objet complet.
<?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.
);
Scénarios courants
Effectuer un téléchargement multipartie et configurer un rappel de téléchargement
Références
Pour consulter l'exemple de code complet relatif au téléchargement multipartie, rendez-vous sur GitHub sample.