Sample code for 30+ languages & platforms
C++ Requires Chilkat v11.6.0+

Amazon S3: Copy an Object Using Multipart Copy

See more S3 - REST Examples

Copy an object inside a general purpose bucket without downloading it. Initiate a destination upload, issue UploadPartCopy ranges, and complete it with the exact returned ETags. Requires source read and destination write permissions, plus applicable KMS permissions. HTTP 200 copy/completion bodies are checked for embedded errors.

The example uses 1,000,000,000-byte parts and supports objects larger than 5 MiB through 10,000,000,000,000 bytes (10 TB), with up to 10,000 parts. Decimal-string offset construction avoids int64 and 32-bit overflow. This is an example limit, not S3’s maximum object size; larger objects require larger parts. Only the final part may be below 5 MiB.

A source version is pinned when returned by HEAD, and every part uses the original ETag condition. Choose a distinct destination key; completing can replace that key or create a new version. Metadata and tags are not automatically inherited by multipart initiation; set the desired destination metadata, content type and encryption there. The source remains unchanged.

The saved s3-multipart.json can be used with the existing abort example after a failure. Completion XML is saved only after all copy parts succeed. Do not restart into the same state file blindly; an uncertain initiation/completion needs inspection. This example does not implement selective resume, and incomplete parts incur charges until completed or aborted.

For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.

Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.

Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.

AWS UploadPartCopy reference

Chilkat C++ Downloads

C++
#include <CkStringBuilder.h>
#include <CkJsonObject.h>
#include <CkAuthAws.h>
#include <CkRest.h>
#include <CkSocket.h>
#include <CkXml.h>
#include <CkFileAccess.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  StringBuilder compares text by value in every generated language.
    CkStringBuilder textCompare;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;
    //  Private configuration, not a file in public web content or source control.
    //  Load current IAM credentials authorized for the S3 operation.
    CkJsonObject credentials;
    credentials.put_Strict(true);
    success = credentials.LoadFile("qa_data/aws/s3.json");
    if (success != true) {
        std::cout << "Could not load private AWS credentials." << "\r\n";
        return;
    }

    textCompare.Clear();
    textCompare.SetString(credentials.stringOf("access_key"));
    bool sameText1 = textCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("access_key") != 1) || (sameText1 == true)) {
        std::cout << "Missing or invalid access_key." << "\r\n";
        return;
    }

    textCompare.Clear();
    textCompare.SetString(credentials.stringOf("secret_key"));
    bool sameText2 = textCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("secret_key") != 1) || (sameText2 == true)) {
        std::cout << "Missing or invalid secret_key." << "\r\n";
        return;
    }

    //  General purpose bucket in the commercial AWS partition.
    const char *region = "us-west-2";
    const char *bucketName = "amzn-s3-demo-bucket";
    CkStringBuilder endpoint;
    success = endpoint.Append(bucketName);
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    success = endpoint.Append(".");
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    success = endpoint.Append("s3.");
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    success = endpoint.Append(region);
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    success = endpoint.Append(".amazonaws.com");
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    CkAuthAws aws;
    aws.put_AccessKey(credentials.stringOf("access_key"));
    aws.put_SecretKey(credentials.stringOf("secret_key"));
    aws.put_Region(region);
    aws.put_ServiceName("s3");
    aws.put_SignatureVersion(4);
    CkRest rest;
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    success = rest.SetAuthAws(aws);
    if (success != true) {
        std::cout << "Could not configure AWS signing." << "\r\n";
        return;
    }

    //  Temporary credentials require this token in every signed query.
    //  Keep request URLs private. Do not clear this parameter between requests.
    if (credentials.HasMember("session_token") == true) {
        if (credentials.JsonTypeOf("session_token") != 1) {
            std::cout << "session_token must be a string." << "\r\n";
            return;
        }

        textCompare.Clear();
        textCompare.SetString(credentials.stringOf("session_token"));
        bool sameText3 = textCompare.ContentsEqual("",true);
        if (sameText3 != true) {
            success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"));
            if (success != true) {
                std::cout << "Could not prepare the request." << "\r\n";
                return;
            }

        }

    }

    //  Connect to the SAME hostname used for TLS verification and request signing.
    CkSocket connection;
    connection.put_RequireSslCertVerify(true);
    connection.put_MaxReadIdleMs(60000);
    connection.put_MaxSendIdleMs(60000);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        std::cout << "TLS connection failed; inspect diagnostics privately." << "\r\n";
        return;
    }

    success = rest.UseConnection(connection,true);
    if (success != true) {
        std::cout << "Could not attach the TLS connection." << "\r\n";
        return;
    }

    CkXml xml;
    xml.put_Strict(true);
    //  Supply an unencoded object key, not a URL. Preserve slashes in the key.
    const char *objectKey = "documents/source.bin";
    CkStringBuilder objectPath;
    success = objectPath.Append(objectKey);
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    success = objectPath.Encode("url_rfc3986","utf-8");
    if (success != true) {
        std::cout << "Could not encode the object key." << "\r\n";
        return;
    }

    int restoredSlashes = objectPath.Replace("%2F","/");
    success = objectPath.Prepend("/");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.SendReqNoBody("HEAD",objectPath.getAsString());
    if (success != true) {
        std::cout << "Could not send HEAD request." << "\r\n";
        return;
    }

    int statusCode = rest.ReadResponseHeader();
    if (statusCode < 0) {
        std::cout << "Could not read the response header." << "\r\n";
        return;
    }

    if (statusCode != 200) {
        std::cout << "HEAD did not return HTTP 200. A 403 is not proof that an object is missing." << "\r\n";
        return;
    }

    //  HEAD has no response body; do not call a body-reading method.
    const char *sourceEtag = rest.responseHdrByName("ETag");
    textCompare.Clear();
    textCompare.SetString(sourceEtag);
    bool sameText4 = textCompare.ContentsEqual("",true);
    if ((rest.get_LastMethodSuccess() != true) || (sameText4 == true)) {
        std::cout << "Missing response header: ETag" << "\r\n";
        return;
    }

    const char *sourceSize = rest.responseHdrByName("Content-Length");
    textCompare.Clear();
    textCompare.SetString(sourceSize);
    bool sameText5 = textCompare.ContentsEqual("",true);
    if ((rest.get_LastMethodSuccess() != true) || (sameText5 == true)) {
        std::cout << "Missing response header: Content-Length" << "\r\n";
        return;
    }

    const char *sourceVersion = rest.responseHdrByName("x-amz-version-id");
    if (rest.get_LastMethodSuccess() != true) {
        sourceVersion = "";
    }

    //  Split a decimal size into billions and a remainder. No large integer type.
    CkStringBuilder sizeText;
    CkStringBuilder digits;
    CkStringBuilder piece;
    success = sizeText.Append(sourceSize);
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    success = digits.Append("0123456789");
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    if ((sizeText.get_Length() < 1) || (sizeText.get_Length() > 14)) {
        std::cout << "Invalid source length for this example." << "\r\n";
        return;
    }

    int position = 0;
    while ((position < sizeText.get_Length())) {
        const char *digit = sizeText.getRange(position,1,false);
        if (digits.Contains(digit,true) != true) {
            std::cout << "Source length is not decimal." << "\r\n";
            return;
        }

        position = position + 1;
    }

    int fullBillions = 0;
    int tailBytes = 0;
    if (sizeText.get_Length() > 9) {
        success = piece.SetString(sizeText.getRange(0,sizeText.get_Length() - 9,false));
        if (success != true) {
            std::cout << "Could not prepare the request." << "\r\n";
            return;
        }

        fullBillions = piece.get_IntValue();
        success = piece.SetString(sizeText.getRange(sizeText.get_Length() - 9,9,false));
        if (success != true) {
            std::cout << "Could not prepare the request." << "\r\n";
            return;
        }

        tailBytes = piece.get_IntValue();
    }
    else {
        tailBytes = sizeText.get_IntValue();
    }

    int numParts = fullBillions;
    if (tailBytes > 0) {
        numParts = numParts + 1;
    }

    if ((numParts < 1) || (numParts > 10000)) {
        std::cout << "This example supports objects through 10 TB using 1 GB parts." << "\r\n";
        return;
    }

    if ((fullBillions == 0) && (tailBytes <= 5242880)) {
        std::cout << "Use CopyObject for sources of 5 MiB or less; ranged copy requires a larger source." << "\r\n";
        return;
    }

    CkFileAccess files;
    if (files.FileExists("s3-multipart.json") == true) {
        std::cout << "A multipart state file already exists; finish or abort that upload first." << "\r\n";
        return;
    }

    CkStringBuilder copySource;
    success = copySource.Append("/");
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    success = copySource.Append(bucketName);
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    success = copySource.Append(objectPath.getAsString());
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    textCompare.Clear();
    textCompare.SetString(sourceVersion);
    bool sameText6 = textCompare.ContentsEqual("",true);
    if (sameText6 != true) {
        CkStringBuilder encodedVersion;
        success = encodedVersion.Append(sourceVersion);
        if (success != true) {
            std::cout << "Could not build text." << "\r\n";
            return;
        }

        success = encodedVersion.Encode("url_rfc3986","utf-8");
        if (success != true) {
            std::cout << "Could not prepare the request." << "\r\n";
            return;
        }

        success = copySource.Append("?versionId=");
        if (success != true) {
            std::cout << "Could not build text." << "\r\n";
            return;
        }

        success = copySource.Append(encodedVersion.getAsString());
        if (success != true) {
            std::cout << "Could not build text." << "\r\n";
            return;
        }

    }

    //  Destination is a DIFFERENT key in this bucket. Existing destination is replaced.
    const char *destinationKey = "documents/copy.bin";
    textCompare.Clear();
    textCompare.SetString(destinationKey);
    bool sameText7 = textCompare.ContentsEqual(objectKey,true);
    if (sameText7 == true) {
        std::cout << "Choose a destination key different from the source." << "\r\n";
        return;
    }

    success = objectPath.SetString(destinationKey);
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = objectPath.Encode("url_rfc3986","utf-8");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    int destinationSlashes = objectPath.Replace("%2F","/");
    success = objectPath.Prepend("/");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.AddQueryParam("uploads","");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.AddHeader("Content-Type","application/octet-stream");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    const char *responseBody = rest.fullRequestNoBody("POST",objectPath.getAsString());
    if (rest.get_LastMethodSuccess() != true) {
        std::cout << "Request did not complete; inspect diagnostics privately." << "\r\n";
        return;
    }

    if (rest.get_ResponseStatusCode() != 200) {
        std::cout << "S3 HTTP status: " << rest.get_ResponseStatusCode() << "\r\n";
        success = xml.LoadXml(responseBody);
        textCompare.Clear();
        textCompare.SetString(xml.tag());
        bool sameText8 = textCompare.ContentsEqual("Error",true);
        if ((success == true) && (sameText8 == true)) {
            std::cout << "S3 error code: " << xml.getChildContent("Code") << "\r\n";
        }

        //  Keep signed headers, credentials, URLs, and full diagnostics private.
        //  A timeout may leave a write's outcome uncertain. Check before retrying.
        return;
    }

    success = xml.LoadXml(responseBody);
    if (success != true) {
        std::cout << "Expected well-formed XML." << "\r\n";
        return;
    }

    textCompare.Clear();
    textCompare.SetString(xml.tag());
    bool sameText9 = textCompare.ContentsEqual("InitiateMultipartUploadResult",true);
    if (sameText9 != true) {
        std::cout << "Unexpected S3 response element; this is not a successful result." << "\r\n";
        return;
    }

    textCompare.Clear();
    textCompare.SetString(xml.getChildContent("UploadId"));
    bool sameText10 = textCompare.ContentsEqual("",true);
    if ((xml.HasChildWithTag("UploadId") != true) || (sameText10 == true)) {
        std::cout << "Missing response field: UploadId" << "\r\n";
        return;
    }

    const char *uploadId = xml.getChildContent("UploadId");
    CkJsonObject state;
    success = state.UpdateString("bucket",bucketName);
    if (success != true) {
        std::cout << "Could not build saved state." << "\r\n";
        return;
    }

    success = state.UpdateString("region",region);
    if (success != true) {
        std::cout << "Could not build saved state." << "\r\n";
        return;
    }

    success = state.UpdateString("key",destinationKey);
    if (success != true) {
        std::cout << "Could not build saved state." << "\r\n";
        return;
    }

    success = state.UpdateString("upload_id",uploadId);
    if (success != true) {
        std::cout << "Could not build saved state." << "\r\n";
        return;
    }

    success = state.UpdateString("source_key",objectKey);
    if (success != true) {
        std::cout << "Could not build saved state." << "\r\n";
        return;
    }

    success = state.UpdateString("source_etag",sourceEtag);
    if (success != true) {
        std::cout << "Could not build saved state." << "\r\n";
        return;
    }

    success = state.UpdateString("source_size",sourceSize);
    if (success != true) {
        std::cout << "Could not build saved state." << "\r\n";
        return;
    }

    success = state.WriteFile("s3-multipart.json");
    if (success != true) {
        std::cout << "Upload initiated but saving state failed; recover the upload ID or list unfinished uploads." << "\r\n";
        return;
    }

    success = rest.RemoveQueryParam("uploads");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.RemoveHeader("Content-Type");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.AddQueryParam("uploadId",uploadId);
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.AddHeader("x-amz-copy-source",copySource.getAsString());
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.AddHeader("x-amz-copy-source-if-match",sourceEtag);
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    CkXml parts;
    parts.put_Tag("CompleteMultipartUpload");
    CkStringBuilder range;
    CkStringBuilder ending;
    CkStringBuilder number;
    int partNumber = 1;
    while ((partNumber <= numParts)) {
        range.Clear();
        ending.Clear();
        number.Clear();
        success = range.Append("bytes=");
        if (success != true) {
            std::cout << "Could not build text." << "\r\n";
            return;
        }

        if (partNumber == 1) {
            success = range.Append("0");
            if (success != true) {
                std::cout << "Could not build text." << "\r\n";
                return;
            }

        }
        else {
            success = range.AppendInt(partNumber - 1);
            if (success != true) {
                std::cout << "Could not prepare the request." << "\r\n";
                return;
            }

            success = range.Append("000000000");
            if (success != true) {
                std::cout << "Could not build text." << "\r\n";
                return;
            }

        }

        success = range.Append("-");
        if (success != true) {
            std::cout << "Could not build text." << "\r\n";
            return;
        }

        if (partNumber <= fullBillions) {
            if (partNumber > 1) {
                success = ending.AppendInt(partNumber - 1);
                if (success != true) {
                    std::cout << "Could not prepare the request." << "\r\n";
                    return;
                }

            }

            success = ending.Append("999999999");
            if (success != true) {
                std::cout << "Could not build text." << "\r\n";
                return;
            }

        }
        else {
            success = ending.AppendInt(tailBytes - 1);
            if (success != true) {
                std::cout << "Could not prepare the request." << "\r\n";
                return;
            }

            if (fullBillions > 0) {
                while ((ending.get_Length() < 9)) {
                    success = ending.Prepend("0");
                    if (success != true) {
                        std::cout << "Could not prepare the request." << "\r\n";
                        return;
                    }

                }

                success = number.AppendInt(fullBillions);
                if (success != true) {
                    std::cout << "Could not prepare the request." << "\r\n";
                    return;
                }

                success = ending.Prepend(number.getAsString());
                if (success != true) {
                    std::cout << "Could not prepare the request." << "\r\n";
                    return;
                }

            }

        }

        success = range.Append(ending.getAsString());
        if (success != true) {
            std::cout << "Could not build text." << "\r\n";
            return;
        }

        number.Clear();
        success = number.AppendInt(partNumber);
        if (success != true) {
            std::cout << "Could not prepare the request." << "\r\n";
            return;
        }

        if (partNumber > 1) {
            success = rest.RemoveQueryParam("partNumber");
            if (success != true) {
                std::cout << "Could not prepare the request." << "\r\n";
                return;
            }

            success = rest.RemoveHeader("x-amz-copy-source-range");
            if (success != true) {
                std::cout << "Could not prepare the request." << "\r\n";
                return;
            }

        }

        success = rest.AddQueryParam("partNumber",number.getAsString());
        if (success != true) {
            std::cout << "Could not prepare the request." << "\r\n";
            return;
        }

        success = rest.AddHeader("x-amz-copy-source-range",range.getAsString());
        if (success != true) {
            std::cout << "Could not prepare the request." << "\r\n";
            return;
        }

        responseBody = rest.fullRequestNoBody("PUT",objectPath.getAsString());
        if (rest.get_LastMethodSuccess() != true) {
            std::cout << "Request did not complete; inspect diagnostics privately." << "\r\n";
            return;
        }

        if (rest.get_ResponseStatusCode() != 200) {
            std::cout << "S3 HTTP status: " << rest.get_ResponseStatusCode() << "\r\n";
            success = xml.LoadXml(responseBody);
            textCompare.Clear();
            textCompare.SetString(xml.tag());
            bool sameText11 = textCompare.ContentsEqual("Error",true);
            if ((success == true) && (sameText11 == true)) {
                std::cout << "S3 error code: " << xml.getChildContent("Code") << "\r\n";
            }

            //  Keep signed headers, credentials, URLs, and full diagnostics private.
            //  A timeout may leave a write's outcome uncertain. Check before retrying.
            return;
        }

        success = xml.LoadXml(responseBody);
        if (success != true) {
            std::cout << "Expected well-formed XML." << "\r\n";
            return;
        }

        textCompare.Clear();
        textCompare.SetString(xml.tag());
        bool sameText12 = textCompare.ContentsEqual("CopyPartResult",true);
        if (sameText12 != true) {
            std::cout << "Unexpected S3 response element; this is not a successful result." << "\r\n";
            return;
        }

        textCompare.Clear();
        textCompare.SetString(xml.getChildContent("ETag"));
        bool sameText13 = textCompare.ContentsEqual("",true);
        if ((xml.HasChildWithTag("ETag") != true) || (sameText13 == true)) {
            std::cout << "Missing response field: ETag" << "\r\n";
            return;
        }

        parts.put_I(partNumber - 1);
        parts.UpdateChildContentInt("Part[i]|PartNumber",partNumber);
        parts.UpdateChildContent("Part[i]|ETag",xml.getChildContent("ETag"));
        std::cout << "Copied part: " << partNumber << "\r\n";
        partNumber = partNumber + 1;
    }

    success = state.UpdateString("completion_xml",parts.getXml());
    if (success != true) {
        std::cout << "Could not build saved state." << "\r\n";
        return;
    }

    success = state.WriteFile("s3-multipart.json");
    if (success != true) {
        std::cout << "Parts copied but completion state could not be saved." << "\r\n";
        return;
    }

    success = rest.RemoveHeader("x-amz-copy-source");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.RemoveHeader("x-amz-copy-source-if-match");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.RemoveHeader("x-amz-copy-source-range");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.RemoveQueryParam("partNumber");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.AddHeader("Content-Type","application/xml");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    responseBody = rest.fullRequestString("POST",objectPath.getAsString(),parts.getXml());
    if (rest.get_LastMethodSuccess() != true) {
        std::cout << "Request did not complete; inspect diagnostics privately." << "\r\n";
        return;
    }

    if (rest.get_ResponseStatusCode() != 200) {
        std::cout << "S3 HTTP status: " << rest.get_ResponseStatusCode() << "\r\n";
        success = xml.LoadXml(responseBody);
        textCompare.Clear();
        textCompare.SetString(xml.tag());
        bool sameText14 = textCompare.ContentsEqual("Error",true);
        if ((success == true) && (sameText14 == true)) {
            std::cout << "S3 error code: " << xml.getChildContent("Code") << "\r\n";
        }

        //  Keep signed headers, credentials, URLs, and full diagnostics private.
        //  A timeout may leave a write's outcome uncertain. Check before retrying.
        return;
    }

    success = xml.LoadXml(responseBody);
    if (success != true) {
        std::cout << "Expected well-formed XML." << "\r\n";
        return;
    }

    textCompare.Clear();
    textCompare.SetString(xml.tag());
    bool sameText15 = textCompare.ContentsEqual("CompleteMultipartUploadResult",true);
    if (sameText15 != true) {
        std::cout << "Unexpected S3 response element; this is not a successful result." << "\r\n";
        return;
    }

    textCompare.Clear();
    textCompare.SetString(xml.getChildContent("ETag"));
    bool sameText16 = textCompare.ContentsEqual("",true);
    if ((xml.HasChildWithTag("ETag") != true) || (sameText16 == true)) {
        std::cout << "Missing response field: ETag" << "\r\n";
        return;
    }

    std::cout << "Multipart copy completed; source was not deleted." << "\r\n";
    //  Archive s3-multipart.json after confirming the destination.
    }