Copiez des objets au sein d'un même bucket ou entre des buckets situés dans la même région.
Notes
Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un endpoint interne. Pour plus de détails sur les régions et endpoints pris en charge, consultez Régions et endpoints.
Dans cette rubrique, les identifiants d'accès sont obtenus à partir des variables d'environnement. Pour plus d'informations, consultez Configurer les identifiants d'accès.
Cette rubrique illustre la création d'une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Configuration du client.
Vous devez disposer des autorisations de lecture sur l'objet source et des autorisations de lecture/écriture sur le bucket de destination.
Les buckets source et de destination ne doivent pas avoir de politiques de rétention configurées. Dans le cas contraire, la copie échoue et l'erreur The object you specified is immutable. est renvoyée.
La copie inter-régions n'est pas prise en charge. Par exemple, vous ne pouvez pas copier un objet d'un bucket situé en Chine (Hangzhou) vers un bucket situé en Chine (Qingdao).
Autorisations
Par défaut, un compte Alibaba Cloud dispose de toutes les autorisations. Les utilisateurs RAM ou les rôles RAM associés à un compte Alibaba Cloud ne disposent d'aucune autorisation par défaut. Le compte Alibaba Cloud ou l'administrateur du compte doit accorder les autorisations d'opération via des politiques RAM ou une politique de bucket.
|
API |
Action |
Description |
|
CopyObject |
|
Copie des objets au sein d'un bucket ou entre des buckets situés dans la même région. |
|
|
||
|
|
Si vous spécifiez la version de l'objet source via versionId, cette autorisation est également requise. |
|
|
|
Si vous copiez les tags d'objet via x-oss-tagging, ces autorisations sont requises. |
|
|
|
||
|
|
Si vous spécifiez les tags d'une version spécifique de l'objet source via versionId, cette autorisation est également requise. |
|
|
|
Lors de la copie d'un objet, si les métadonnées de l'objet de destination contiennent X-Oss-Server-Side-Encryption: KMS, ces deux autorisations sont requises. |
|
|
|
Copier un petit objet
Utilisez la méthode copy pour copier un objet dont la taille est inférieure ou égale à 1 Go au sein du même bucket ou vers un autre bucket dans la même région.
-
Copier un objet au sein du même bucket
L'exemple de code suivant montre comment copier un objet au sein du même bucket.
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. Example: examplebucket. bucket: 'examplebucket', // Specify whether to enable HTTPS. If you set secure to true, HTTPS is enabled. // secure: true }) // Copy an object within a bucket. async function copySmallObjecInSameBucket() { try { // Specify the full paths of the destination object and source object. Do not include the bucket name in the full paths. // Specify HTTP headers and custom metadata for the destination object. const result = await client.copy('destexampleobject.txt', 'srcexampleobject.txt', { // Configure the headers parameter to specify HTTP headers for the destination object. If you do not configure the headers parameter, the HTTP headers of the destination object are the same as the HTTP headers of the source object. The HTTP headers of the source object are copied. headers: { 'Cache-Control': 'no-cache', // If the ETag value of the source object is the same as the ETag value specified in the request, OSS copies the object and returns 200 OK. 'if-match': '5B3C1A2E053D763E1B002CC607C5****', // If the ETag value that you specify in the request is different from the ETag value of the source object, OSS copies the object and returns 200 OK. 'if-none-match': '5B3C1A2E053D763E1B002CC607C5****', // If the time that is specified in the request is earlier than the time when the object is modified, OSS copies the object and returns 200 OK. 'if-modified-since': '2021-12-09T07:01:56.000Z', // If the source object has not been modified since the specified time, the object is copied and 200 OK is returned. 'if-unmodified-since': '2021-12-09T07:01:56.000Z', // Specify the access control list (ACL) of the destination object. In this example, the ACL is set to private, which indicates that only the object owner and authorized users have read and write permissions on the object. Other users do not have permissions to access the object. 'x-oss-object-acl': 'private', // Specify tags for the object. You can specify multiple tags for the object at the same time. 'x-oss-tagging': 'Tag1=1&Tag2=2', // Specify whether the CopyObject operation overwrites an existing object that has the same name. In this example, this parameter is set to true, which specifies that the CopyObject operation does not overwrite an existing object that has the same name. 'x-oss-forbid-overwrite': 'true', }, // Configure the meta parameter to specify the metadata of the destination object. If you do not configure the meta parameter, the metadata of the destination object is the same as the metadata of the source object. The metadata of the source object is copied. meta: { location: 'hangzhou', year: 2015, people: 'mary', }, }); console.log(result); } catch (e) { console.log(e); } } copySmallObjecInSameBucket() -
Copier un objet entre des buckets dans la même région
L'exemple de code suivant montre comment copier un objet entre des buckets situés dans la même région.
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 destination bucket. bucket: 'destexamplebucket', }); async function copySmallObjectBetweenBuckets() { try { // Specify the name of the destination object destobject.txt, the name of the source object srcobject.txt, and the name of the bucket to which the source object belongs. const result = await client.copy('destobject.txt', 'srcobject.txt', 'srcbucket', { // Configure the headers parameter to specify HTTP headers for the destination object. If you do not configure the headers parameter, the HTTP headers of the destination object are the same as the HTTP headers of the source object. The HTTP headers of the source object are copied. headers: { 'Cache-Control': 'no-cache', }, // Configure the meta parameter to specify the metadata of the destination object. If you do not configure the meta parameter, the metadata of the destination object is the same as the metadata of the source object. The metadata of the source object is copied. meta: { location: 'hangzhou', year: 2015, people: 'mary', }, }); console.log(result); } catch (e) { console.log(e); } } copySmallObjectBetweenBuckets()
Copier un grand objet
Pour les objets de plus de 1 Go, utilisez la méthode multipartUploadCopy pour effectuer une copie multipartie.
L'exemple de code suivant montre comment copier un objet entre des buckets situés dans la même région.
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 destination bucket.
bucket: "destexamplebucket",
});
async function copyLargeObjectBetweenDifferentBuckets() {
try {
const copyheaders = {
// If the ETag value of the source object is the same as the ETag value that is specified in the request, OSS copies the object. Otherwise, OSS returns the HTTP status code 412 (PreconditionFailed).
"x-oss-copy-source-if-match": "5B3C1A2E053D763E1B002CC607C5****",
// If the ETag value of the source object is different from the ETag value that is specified in the request, OSS copies the object and returns 200 OK. Otherwise, OSS returns the HTTP status code 304 (NotModified).
"x-oss-copy-source-if-none-match": "5B3C1A2E053D763E1B002CC607C5****",
// If the time that is specified in the request is later than or the same as the time when the object is modified, OSS copies the object and returns 200 OK. Otherwise, OSS returns the HTTP status code 412 (PreconditionFailed).
"x-oss-copy-source-if-unmodified-since": "2022-12-09T07:01:56.000Z",
// If the time that is specified in the request is earlier than the time when the object is modified, OSS copies the object and returns 200 OK. Otherwise, OSS returns the HTTP status code 304 (NotModified).
"x-oss-copy-source-if-modified-since": "2022-12-09T07:01:56.000Z",
};
const headers = {
// Specify the caching behavior of the web page when the object is downloaded.
"Cache-Control": "no-cache",
// Specify the name of the object when the object is downloaded.
"Content-Disposition": "somename",
// Specify the expiration time in milliseconds.
Expires: "1000",
};
let savedCpt;
// Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destexampleobject1.txt.
const r1 = await client.multipartUploadCopy("destexampleobject1.txt", {
// Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcexampleobject.txt.
sourceKey: "srcexampleobject.txt",
// Specify the name of the source bucket. Example: sourcebucket.
sourceBucketName: "sourcebucket",
copyheaders: copyheaders,
});
console.log(r1);
// Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destexampleobject2.txt.
const r2 = await client.multipartUploadCopy("destexampleobject2.txt", {
// Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcexampleobject.txt.
sourceKey: "srcexampleobject.txt",
// Specify the name of the source bucket. Example: sourcebucket.
sourceBucketName: "sourcebucket",
}, {
// Set the number of parts that can be uploaded in parallel.
parallel: 4,
// Set the part size.
partSize: 1024 * 1024,
progress: function (p, cpt, res) {
console.log(p);
savedCpt = cpt;
console.log(cpt);
console.log(res.headers["x-oss-request-id"]);
},
headers: headers,
copyheaders: copyheaders,
});
console.log(r2);
// Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destexampleobject3.txt.
const r3 = await client.multipartUploadCopy("destexampleobject3.txt", {
// Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcexampleobject.txt.
sourceKey: "srcexampleobject.txt",
// Specify the name of the source bucket. Example: sourcebucket.
sourceBucketName: "sourcebucket",
}, {
checkpoint: savedCpt,
progress: function (p, cpt, res) {
console.log(p);
console.log(cpt);
console.log(res.headers["x-oss-request-id"]);
},
});
console.log(r3);
} catch (e) {
console.log(e);
}
}
copyLargeObjectBetweenDifferentBuckets()
Références
-
Copier un petit objet
Pour obtenir l'exemple de code complet relatif à la copie d'un petit objet, consultez l'exemple GitHub.
Pour plus d'informations sur l'opération API permettant de copier un petit objet, consultez CopyObject.
-
Copier un grand objet
Pour obtenir l'exemple de code complet relatif à la copie d'un grand objet, consultez l'exemple GitHub.
Pour plus d'informations sur l'opération API permettant de copier un grand objet, consultez UploadPartCopy.