Copie objetos dentro de um mesmo bucket ou entre buckets na mesma região.
Observações de uso
Neste tópico, utiliza-se o endpoint público da região china (Hangzhou). Caso precise acessar o OSS a partir de outros service da alibaba cloud na mesma região, defina um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.
Este tópico demonstra como crie uma instância OSSClient com um endpoint do OSS. Para configure alternativas, como o uso de um domínio personalizado ou autenticação com credenciais do Security Token service (STS), consulte Create an OssClient instance.
Para copiar um objeto, é necessário ter permissões de leitura no objeto de origem, além de permissões de leitura e gravação no bucket de destino.
Certifique-se de que não existem políticas de retenção configuradas para o bucket de origem e o bucket de destino. Caso contrário, o sistema retornará a mensagem de erro The object you specified is immutable..
O bucket de origem e o bucket de destino devem estar na mesma região. Por exemplo, objetos em um bucket localizado na região china (Hangzhou) não podem ser copiados para outro bucket localizado na região china (Qingdao).
Copiar um objeto pequeno
Chame o método client.CopyObject para copiar um objeto menor que 1 GB de um bucket de origem para um bucket de destino na mesma região. A tabela a seguir descreve os parâmetros que você deve configure ao chamar client.CopyObject.
|
Método de configuração |
Descrição |
|
CopyObjectOutcome OssClient::CopyObject(const CopyObjectRequest &request) |
Permite que você especifique os metadados do objeto de destino e as condições de cópia. Se as URLs do objeto de origem e do objeto de destino forem iguais, os metadados especificados na solicitação substituirão os metadados do objeto de origem. |
execute o código a seguir para copiar um objeto pequeno:
#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;
}
Copiar um objeto grande
Para objetos maiores que 1 GB, use a cópia multipart (UploadPartCopy). O processo possui três etapas:
Use client.InitiateMultipartUpload para iniciar uma tarefa de cópia multipart.
Use client.UploadPartCopy para copiar as partes. Todas as partes devem ser maiores que 100 KB, exceto a última.
Use client.CompleteMultipartUpload para concluir a tarefa de cópia multipart.
execute o código a seguir para copiar um objeto grande:
#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;
}
Referências
Para acessar o source completo usado para copiar objetos grandes e pequenos, visite o GitHub.
Para obter mais informações sobre a operação de API que você pode chamar para copiar um objeto pequeno, consulte CopyObject.
Para obter mais informações sobre a operação de API que você pode chamar para copiar um objeto grande, consulte UploadPartCopy.