Le téléversement multipart d'OSS divise les objets volumineux en parties afin de permettre un envoi indépendant et reprenable. Une fois toutes les parties téléversées, OSS les assemble pour former un objet complet.
Notes d'utilisation
La méthode multipartUpload découpe un objet en plusieurs parties et les téléverse individuellement. En cas d'interruption, seules les parties échouées ou manquantes sont renvoyées.
Privilégiez le téléversement multipart pour les objets dépassant 100 Mo. Pour les objets plus petits, optez pour un téléversement simple. Avec des fichiers de petite taille, une valeur inadaptée du paramètre partSize peut fausser le rapport de progression.
Si une erreur ConnectionTimeoutError survient lors d'un MultipartUpload, réduisez la taille des parties, augmentez le délai d'expiration ou renvoyez la requête. Pour identifier la cause racine, capturez l'erreur ConnectionTimeoutError. Consultez les rubriques Gestion des délais d'expiration de connexion réseau.
Le tableau ci-dessous présente les paramètres disponibles pour le téléversement multipart.
|
Catégorie |
Paramètre |
Description |
|
Paramètres obligatoires |
name {String} |
Chemin complet de l'objet, hors nom du bucket. |
|
file {String|File} |
Chemin du fichier local ou fichier HTML5 à téléverser. |
|
|
[options] {Object} Paramètres facultatifs |
[checkpoint] {Object} |
Enregistre la progression du téléversement multipart pour permettre la reprise. Obligatoire lorsque la reprise est activée. Si une partie échoue, OSS reprend depuis le point enregistré. Le fichier de checkpoint est supprimé à la fin du téléversement. |
|
[parallel] {Number} |
Nombre de téléversements de parties simultanés. Valeur par défaut : 5. |
|
|
[partSize] {Number} |
Taille de chaque partie. Plages valides : de 100 Ko à 5 Go. Valeur par défaut : 1 Mo. |
|
|
[progress] {Function} |
Fonction de rappel indiquant la progression du téléversement. Peut être asynchrone. Paramètres :
|
|
|
[meta] {Object} |
Métadonnées personnalisées. Les en-têtes sont préfixés par |
|
|
[mime] {String} |
En-tête de requête Content-Type. |
|
|
[headers] {Object} |
Autres en-têtes HTTP définis dans la RFC 2616. Exemples :
|
Exemple de téléversement multipart
Le SDK OSS pour Node.js ne prend pas en charge la vérification MD5 lors du téléversement multipart. Pour valider l'intégrité des données, utilisez la bibliothèque CRC-64 une fois le téléversement terminé.
L'exemple suivant illustre l'utilisation de la méthode multipartUpload pour effectuer un téléversement multipart :
const OSS = require('ali-oss');
const path = require("path");
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'yourbucketname',
});
const progress = (p, _checkpoint) => {
// Record the upload progress of the object.
console.log(p);
// Record the checkpoint information about the multipart upload task.
console.log(_checkpoint);
};
const headers = {
// Specify the storage class of the object.
'x-oss-storage-class': 'Standard',
// Specify tags for the object. You can specify multiple tags for the object.
'x-oss-tagging': 'Tag1=1&Tag2=2',
// Specify whether to overwite an existing object with the same name when the multipart upload task is initialized. In this example, this parameter is set to true, which indicates that an existing object with the same name as the object to upload is not overwritten.
'x-oss-forbid-overwrite': 'true'
}
// Start the multipart upload task.
async function multipartUpload() {
try {
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Then, specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. Do not include the bucket name in the full path.
// By default, if you set this parameter to the name of a local file such as examplefile.txt without specifying the local path, the local file is uploaded from the local path of the project to which the sample program belongs.
const result = await client.multipartUpload('exampledir/exampleobject.txt', path.normalize('D:\\localpath\\examplefile.txt'), {
progress,
// headers,
// Configure the meta parameter to specify metadata for the object. You can call the HeadObject operation to obtain the object metadata.
meta: {
year: 2020,
people: 'test',
},
});
console.log(result);
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
const head = await client.head('exampledir/exampleobject.txt');
console.log(head);
} catch (e) {
// Handle timeout exceptions.
if (e.code === 'ConnectionTimeoutError') {
console.log('TimeoutError');
// do ConnectionTimeoutError operation
}
console.log(e);
}
}
multipartUpload();
La méthode multipartUpload encapsule les opérations initMultipartUpload, uploadPart et completeMultipartUpload. Pour exécuter le téléversement multipart étape par étape, appelez directement ces opérations : .initMultipartUpload, .uploadPart et .completeMultipartUpload.
Annuler un téléversement multipart
Appelez client.abortMultipartUpload pour annuler un téléversement multipart. Cette action invalide l'ID de téléversement et supprime toutes les parties déjà envoyées.
L'exemple suivant annule un téléversement multipart.
const OSS = require("ali-oss");
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: "yourregion",
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "yourbucketname",
});
async function abortMultipartUpload() {
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
const name = "exampledir/exampleobject.txt";
// Specify the upload ID. You can obtain the upload ID from the response to the InitiateMultipartUpload operation.
const uploadId = "0004B999EF518A1FE585B0C9360D****";
const result = await client.abortMultipartUpload(name, uploadId);
console.log(result);
}
abortMultipartUpload();
Répertorier les téléversements multipart en cours
Appelez client.listUploads pour lister tous les téléversements multipart initiés mais non terminés ni annulés.
const OSS = require("ali-oss");
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: "yourregion",
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "yourbucketname",
});
async function listUploads(query = {}) {
// You can configure the following parameters for query: prefix, marker, delimiter, upload-id-marker, and max-uploads.
const result = await client.listUploads(query);
result.uploads.forEach((upload) => {
// Specify the upload IDs of the multipart upload tasks.
console.log(upload.uploadId);
// Combine all parts into a complete object and specify the full path of the object.
console.log(upload.name);
});
}
const query = {
// Specify the maximum number of multipart upload tasks to return for the current list operation. The default value and the maximum value of max-uploads are both 1000.
"max-uploads": 1000,
};
listUploads(query);
Lister les parties téléversées
Appelez client.listParts pour afficher toutes les parties associées à un ID de téléversement spécifique.
const OSS = require("ali-oss");
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: "yourregion",
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "yourbucketname",
});
async function listParts() {
const query = {
// Specify the maximum number of parts to return for the current list operation. The default value and the maximum value of max-parts are both 1000.
"max-parts": 1000,
};
let result;
do {
result = await client.listParts(
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
"exampledir/exampleobject.txt",
// Obtain the upload ID from the response to the InitiateMultipartUpload operation. You must obtain the upload ID before you call the CompleteMultipartUpload operation to complete the multipart upload task.
"0004B999EF518A1FE585B0C9360D****",
query
);
// Specify the starting position of the next list operation. Only parts with part numbers greater than the value of this parameter are listed.
query["part-number-marker"] = result.nextPartNumberMarker;
result.parts.forEach((part) => {
console.log(part.PartNumber);
console.log(part.LastModified);
console.log(part.ETag);
console.log(part.Size);
});
} while (result.isTruncated === "true");
}
listParts();
Références
Exemple de code complet pour le téléversement multipart : GitHub.
-
La méthode
multipartUploadencapsule les opérations API suivantes : -
Opérations API connexes :
AbortMultipartUpload : annule une tâche de téléversement multipart en cours et supprime les parties déjà téléversées.
ListParts : liste toutes les parties correctement téléversées pour une tâche spécifique.
ListMultipartUploads : répertorie toutes les tâches de téléversement multipart actuellement en cours (initiées mais ni terminées ni abandonnées).