Tüm Ürünler
Search
Belge Merkezi

Object Storage Service:Copy objects by using the C++ SDK

Son Güncelleme:Oct 01, 2026

Aynı bölgedeki bir paket içinde veya paketler arasında nesneleri kopyalayın.

Kullanım notları

  • Bu konuda Çin (Hangzhou) bölgesinin genel uç noktası kullanılmıştır. OSS ile aynı bölgedeki diğer Alibaba Cloud hizmetlerinden OSS'ye erişmek için dahili uç noktayı kullanın. OSS bölgeleri ve uç noktaları hakkında daha fazla bilgi için bkz. Bölgeler ve uç noktalar.

  • Bu konu, bir OSS uç noktası kullanarak OssClient örneği oluşturmayı gösterir. Özel etki alanı kullanma veya Security Token Service (STS) kimlik bilgileriyle kimlik doğrulama gibi alternatif yapılandırmalar için bkz. OssClient örneği oluşturun.

  • Bir nesneyi kopyalamak için kaynak nesne üzerinde okuma iznine ve hedef paket üzerinde okuma ve yazma iznine sahip olmanız gerekir.

  • Kaynak paket ve hedef paket için herhangi bir saklama ilkesi yapılandırılmadığından emin olun. Aksi takdirde, The object you specified is immutable. hata mesajı döndürülür.

  • Kaynak paket ve hedef paket aynı bölgede bulunmalıdır. Örneğin, Çin (Hangzhou) bölgesinde bulunan bir paketteki nesneler, Çin (Qingdao) bölgesinde bulunan başka bir pakete kopyalanamaz.

Küçük bir nesneyi kopyalayın

1 GB'dan küçük bir nesneyi aynı bölge içindeki bir kaynak paketten hedef pakete kopyalamak için client.CopyObject yöntemini çağırabilirsiniz. Aşağıdaki tabloda, client.CopyObject yöntemini çağırırken parametrelerin nasıl yapılandırılacağı açıklanmaktadır.


Yapılandırma yöntemi


Açıklama


CopyObjectOutcome OssClient::CopyObject(const CopyObjectRequest &request)


Hedef nesnenin meta verilerini ve kopyalama koşullarını belirtmenize olanak tanır. Kaynak nesnenin ve hedef nesnenin URL'leri aynıysa, istekte belirtilen meta veriler kaynak nesnenin meta verilerinin yerine geçer.

Aşağıdaki kod, küçük bir nesnenin nasıl kopyalanacağına ilişkin bir örnek sunar:

#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;
}

Büyük bir nesneyi kopyalayın

1 GB'tan büyük nesneler için çok parçalı kopyalama (UploadPartCopy) kullanın. Süreç üç adımdan oluşur:

  1. Çok parçalı bir kopyalama görevini başlatmak için client.InitiateMultipartUpload yöntemini kullanın.

  2. Parçaları kopyalamak için client.UploadPartCopy yöntemini kullanın. Son parça hariç tüm parçalar 100 KB'tan büyük olmalıdır.

  3. Çok parçalı kopyalama görevini tamamlamak için client.CompleteMultipartUpload yöntemini kullanın.

Aşağıdaki kod, büyük bir nesnenin nasıl kopyalanacağına ilişkin bir örnek sunar:

#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;
}

İlgili konular

  • Büyük ve küçük bir nesneyi kopyalamak için kullanılan eksiksiz örnek kodu görüntülemek üzere GitHub adresini ziyaret edin.

  • Küçük bir nesneyi kopyalamak için çağırabileceğiniz API işlemi hakkında daha fazla bilgi için bkz. CopyObject.

  • Büyük bir nesneyi kopyalamak için çağırabileceğiniz API işlemi hakkında daha fazla bilgi için bkz. UploadPartCopy.