Copiez des objets au sein d'un même bucket ou entre des buckets situés dans la même région.
Notes d'utilisation
Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez la page Régions et points de terminaison.
Cette rubrique explique comment créer une instance
OSSClientavec un point de terminaison OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du service Security Token Service (STS), reportez-vous à la section Créer une instance OssClient.Pour copier un objet, vous devez disposer des autorisations de lecture sur l'objet source ainsi que des autorisations de lecture et d'écriture sur le bucket de destination.
Assurez-vous qu'aucune politique de rétention n'est configurée pour le bucket source et le bucket de destination. Dans le cas contraire, le message d'erreur The object you specified is immutable. s'affiche.
Le bucket source et le bucket de destination doivent se trouver dans la même région. Par exemple, il est impossible de copier des objets d'un bucket situé dans la région Chine (Hangzhou) vers un autre bucket situé dans la région Chine (Qingdao).
Copier un petit objet
Appelez client.CopyObject pour copier un objet de moins de 1 Go d'un bucket source vers un bucket de destination au sein de la même région. Le tableau suivant décrit la configuration des paramètres lors de l'appel à client.CopyObject.
|
Méthode de configuration |
Description |
|
CopyObjectOutcome OssClient::CopyObject(const CopyObjectRequest &request) |
Permet de spécifier les métadonnées de l'objet de destination et les conditions de copie. Si les URL de l'objet source et de l'objet de destination sont identiques, les métadonnées spécifiées dans la requête remplacent celles de l'objet source. |
L'exemple de code suivant montre comment copier un petit objet :
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* 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 cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the name of the source bucket. Example: srcexamplebucket. */
std::string SourceBucketName = "srcexamplebucket";
/* Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket. Example: destbucket. */
std::string CopyBucketName = "destbucket";
/* Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcdir/scrobject.txt. */
std::string SourceObjectName = "srcdir/scrobject.txt";
/* Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destdir/destobject.txt. */
std::string CopyObjectName = "destdir/destobject.txt";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 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. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
CopyObjectRequest request(CopyBucketName, CopyObjectName);
request.setCopySource(SourceBucketName, SourceObjectName);
/* Copy the object. */
auto outcome = client.CopyObject(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "CopyObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}
Copier un grand objet
Pour les objets de plus de 1 Go, utilisez la copie multipartite (UploadPartCopy). Le processus comporte trois étapes :
Utilisez
client.InitiateMultipartUploadpour initier une tâche de copie multipartite.Utilisez
client.UploadPartCopypour copier les parties. Toutes les parties, sauf la dernière, doivent être supérieures à 100 Ko.Utilisez
client.CompleteMultipartUploadpour finaliser la tâche de copie multipartite.
L'exemple de code suivant montre comment copier un grand objet :
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* 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 cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the name of the source bucket. Example: srcexamplebucket. */
std::string SourceBucketName = "srcexamplebucket";
/* Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket. Example: destbucket. */
std::string CopyBucketName = "destbucket";
/* Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcdir/scrobject.txt. */
std::string SourceObjectName = "srcdir/scrobject.txt";
/* Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destdir/destobject.txt. */
std::string CopyObjectName = "destdir/destobject.txt";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 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. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
auto getObjectMetaReq = GetObjectMetaRequest(SourceBucketName, SourceObjectName);
auto getObjectMetaResult = client.GetObjectMeta(getObjectMetaReq);
if (!getObjectMetaResult.isSuccess()) {
std::cout << "GetObjectMeta fail" <<
",code:" << getObjectMetaResult.error().Code() <<
",message:" << getObjectMetaResult.error().Message() <<
",requestId:" << getObjectMetaResult.error().RequestId() << std::endl;
return -1;
}
/* Query the size of the source object. */
auto objectSize = getObjectMetaResult.result().ContentLength();
/* Copy the large object. */
InitiateMultipartUploadRequest initUploadRequest(CopyBucketName, CopyObjectName);
/* Initiate a multipart copy task. */
auto uploadIdResult = client.InitiateMultipartUpload(initUploadRequest);
auto uploadId = uploadIdResult.result().UploadId();
int64_t partSize = 100 * 1024;
PartList partETagList;
int partCount = static_cast<int>(objectSize / partSize);
/* Calculate the number of parts. */
if (objectSize % partSize != 0) {
partCount++;
}
/* Copy each part. */
for (int i = 1; i <= partCount; i++) {
auto skipBytes = partSize * (i - 1);
auto size = (partSize < objectSize - skipBytes) ? partSize : (objectSize - skipBytes);
auto uploadPartCopyReq = UploadPartCopyRequest(CopyBucketName, CopyObjectName, SourceBucketName, SourceObjectName,uploadId, i);
uploadPartCopyReq.setCopySourceRange(skipBytes, skipBytes + size -1);
auto uploadPartOutcome = client.UploadPartCopy(uploadPartCopyReq);
if (uploadPartOutcome.isSuccess()) {
Part part(i, uploadPartOutcome.result().ETag());
partETagList.push_back(part);
}
else {
std::cout << "UploadPartCopy fail" <<
",code:" << uploadPartOutcome.error().Code() <<
",message:" << uploadPartOutcome.error().Message() <<
",requestId:" << uploadPartOutcome.error().RequestId() << std::endl;
}
}
/* Complete the multipart copy task. */
CompleteMultipartUploadRequest request(CopyBucketName, CopyObjectName, partETagList, uploadId);
auto outcome = client.CompleteMultipartUpload(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "CompleteMultipartUpload fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}
Références
Pour consulter l'exemple de code complet utilisé pour copier un grand objet et un petit objet, rendez-vous sur GitHub.
Pour plus d'informations sur l'opération API permettant de copier un petit objet, consultez la page CopyObject.
Pour plus d'informations sur l'opération API permettant de copier un grand objet, consultez la page UploadPartCopy.