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.
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkSocketW.h>
#include <CkXmlW.h>
#include <CkFileAccessW.h>
void ChilkatSample(void)
{
bool success = false;
// StringBuilder compares text by value in every generated language.
CkStringBuilderW 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.
CkJsonObjectW credentials;
credentials.put_Strict(true);
success = credentials.LoadFile(L"qa_data/aws/s3.json");
if (success != true) {
wprintf(L"Could not load private AWS credentials.\n");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.stringOf(L"access_key"));
bool sameText1 = textCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"access_key") != 1) || (sameText1 == true)) {
wprintf(L"Missing or invalid access_key.\n");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.stringOf(L"secret_key"));
bool sameText2 = textCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"secret_key") != 1) || (sameText2 == true)) {
wprintf(L"Missing or invalid secret_key.\n");
return;
}
// General purpose bucket in the commercial AWS partition.
const wchar_t *region = L"us-west-2";
const wchar_t *bucketName = L"amzn-s3-demo-bucket";
CkStringBuilderW endpoint;
success = endpoint.Append(bucketName);
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = endpoint.Append(L".");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = endpoint.Append(L"s3.");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = endpoint.Append(region);
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = endpoint.Append(L".amazonaws.com");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
CkAuthAwsW aws;
aws.put_AccessKey(credentials.stringOf(L"access_key"));
aws.put_SecretKey(credentials.stringOf(L"secret_key"));
aws.put_Region(region);
aws.put_ServiceName(L"s3");
aws.put_SignatureVersion(4);
CkRestW rest;
rest.put_ConnectTimeoutMs(20000);
rest.put_IdleTimeoutMs(60000);
success = rest.SetAuthAws(aws);
if (success != true) {
wprintf(L"Could not configure AWS signing.\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(L"session_token") == true) {
if (credentials.JsonTypeOf(L"session_token") != 1) {
wprintf(L"session_token must be a string.\n");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.stringOf(L"session_token"));
bool sameText3 = textCompare.ContentsEqual(L"",true);
if (sameText3 != true) {
success = rest.AddQueryParam(L"X-Amz-Security-Token",credentials.stringOf(L"session_token"));
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
}
}
// Connect to the SAME hostname used for TLS verification and request signing.
CkSocketW connection;
connection.put_RequireSslCertVerify(true);
connection.put_MaxReadIdleMs(60000);
connection.put_MaxSendIdleMs(60000);
success = connection.Connect(endpoint.getAsString(),443,true,20000);
if (success != true) {
wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
return;
}
success = rest.UseConnection(connection,true);
if (success != true) {
wprintf(L"Could not attach the TLS connection.\n");
return;
}
CkXmlW xml;
xml.put_Strict(true);
// Supply an unencoded object key, not a URL. Preserve slashes in the key.
const wchar_t *objectKey = L"documents/source.bin";
CkStringBuilderW objectPath;
success = objectPath.Append(objectKey);
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = objectPath.Encode(L"url_rfc3986",L"utf-8");
if (success != true) {
wprintf(L"Could not encode the object key.\n");
return;
}
int restoredSlashes = objectPath.Replace(L"%2F",L"/");
success = objectPath.Prepend(L"/");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.SendReqNoBody(L"HEAD",objectPath.getAsString());
if (success != true) {
wprintf(L"Could not send HEAD request.\n");
return;
}
int statusCode = rest.ReadResponseHeader();
if (statusCode < 0) {
wprintf(L"Could not read the response header.\n");
return;
}
if (statusCode != 200) {
wprintf(L"HEAD did not return HTTP 200. A 403 is not proof that an object is missing.\n");
return;
}
// HEAD has no response body; do not call a body-reading method.
const wchar_t *sourceEtag = rest.responseHdrByName(L"ETag");
textCompare.Clear();
textCompare.SetString(sourceEtag);
bool sameText4 = textCompare.ContentsEqual(L"",true);
if ((rest.get_LastMethodSuccess() != true) || (sameText4 == true)) {
wprintf(L"Missing response header: ETag\n");
return;
}
const wchar_t *sourceSize = rest.responseHdrByName(L"Content-Length");
textCompare.Clear();
textCompare.SetString(sourceSize);
bool sameText5 = textCompare.ContentsEqual(L"",true);
if ((rest.get_LastMethodSuccess() != true) || (sameText5 == true)) {
wprintf(L"Missing response header: Content-Length\n");
return;
}
const wchar_t *sourceVersion = rest.responseHdrByName(L"x-amz-version-id");
if (rest.get_LastMethodSuccess() != true) {
sourceVersion = L"";
}
// Split a decimal size into billions and a remainder. No large integer type.
CkStringBuilderW sizeText;
CkStringBuilderW digits;
CkStringBuilderW piece;
success = sizeText.Append(sourceSize);
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = digits.Append(L"0123456789");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
if ((sizeText.get_Length() < 1) || (sizeText.get_Length() > 14)) {
wprintf(L"Invalid source length for this example.\n");
return;
}
int position = 0;
while ((position < sizeText.get_Length())) {
const wchar_t *digit = sizeText.getRange(position,1,false);
if (digits.Contains(digit,true) != true) {
wprintf(L"Source length is not decimal.\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) {
wprintf(L"Could not prepare the request.\n");
return;
}
fullBillions = piece.get_IntValue();
success = piece.SetString(sizeText.getRange(sizeText.get_Length() - 9,9,false));
if (success != true) {
wprintf(L"Could not prepare the request.\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)) {
wprintf(L"This example supports objects through 10 TB using 1 GB parts.\n");
return;
}
if ((fullBillions == 0) && (tailBytes <= 5242880)) {
wprintf(L"Use CopyObject for sources of 5 MiB or less; ranged copy requires a larger source.\n");
return;
}
CkFileAccessW files;
if (files.FileExists(L"s3-multipart.json") == true) {
wprintf(L"A multipart state file already exists; finish or abort that upload first.\n");
return;
}
CkStringBuilderW copySource;
success = copySource.Append(L"/");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = copySource.Append(bucketName);
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = copySource.Append(objectPath.getAsString());
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
textCompare.Clear();
textCompare.SetString(sourceVersion);
bool sameText6 = textCompare.ContentsEqual(L"",true);
if (sameText6 != true) {
CkStringBuilderW encodedVersion;
success = encodedVersion.Append(sourceVersion);
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = encodedVersion.Encode(L"url_rfc3986",L"utf-8");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = copySource.Append(L"?versionId=");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = copySource.Append(encodedVersion.getAsString());
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
}
// Destination is a DIFFERENT key in this bucket. Existing destination is replaced.
const wchar_t *destinationKey = L"documents/copy.bin";
textCompare.Clear();
textCompare.SetString(destinationKey);
bool sameText7 = textCompare.ContentsEqual(objectKey,true);
if (sameText7 == true) {
wprintf(L"Choose a destination key different from the source.\n");
return;
}
success = objectPath.SetString(destinationKey);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = objectPath.Encode(L"url_rfc3986",L"utf-8");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
int destinationSlashes = objectPath.Replace(L"%2F",L"/");
success = objectPath.Prepend(L"/");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.AddQueryParam(L"uploads",L"");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.AddHeader(L"Content-Type",L"application/octet-stream");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
const wchar_t *responseBody = rest.fullRequestNoBody(L"POST",objectPath.getAsString());
if (rest.get_LastMethodSuccess() != true) {
wprintf(L"Request did not complete; inspect diagnostics privately.\n");
return;
}
if (rest.get_ResponseStatusCode() != 200) {
wprintf(L"S3 HTTP status: %d\n",rest.get_ResponseStatusCode());
success = xml.LoadXml(responseBody);
textCompare.Clear();
textCompare.SetString(xml.tag());
bool sameText8 = textCompare.ContentsEqual(L"Error",true);
if ((success == true) && (sameText8 == true)) {
wprintf(L"S3 error code: %s\n",xml.getChildContent(L"Code"));
}
// 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) {
wprintf(L"Expected well-formed XML.\n");
return;
}
textCompare.Clear();
textCompare.SetString(xml.tag());
bool sameText9 = textCompare.ContentsEqual(L"InitiateMultipartUploadResult",true);
if (sameText9 != true) {
wprintf(L"Unexpected S3 response element; this is not a successful result.\n");
return;
}
textCompare.Clear();
textCompare.SetString(xml.getChildContent(L"UploadId"));
bool sameText10 = textCompare.ContentsEqual(L"",true);
if ((xml.HasChildWithTag(L"UploadId") != true) || (sameText10 == true)) {
wprintf(L"Missing response field: UploadId\n");
return;
}
const wchar_t *uploadId = xml.getChildContent(L"UploadId");
CkJsonObjectW state;
success = state.UpdateString(L"bucket",bucketName);
if (success != true) {
wprintf(L"Could not build saved state.\n");
return;
}
success = state.UpdateString(L"region",region);
if (success != true) {
wprintf(L"Could not build saved state.\n");
return;
}
success = state.UpdateString(L"key",destinationKey);
if (success != true) {
wprintf(L"Could not build saved state.\n");
return;
}
success = state.UpdateString(L"upload_id",uploadId);
if (success != true) {
wprintf(L"Could not build saved state.\n");
return;
}
success = state.UpdateString(L"source_key",objectKey);
if (success != true) {
wprintf(L"Could not build saved state.\n");
return;
}
success = state.UpdateString(L"source_etag",sourceEtag);
if (success != true) {
wprintf(L"Could not build saved state.\n");
return;
}
success = state.UpdateString(L"source_size",sourceSize);
if (success != true) {
wprintf(L"Could not build saved state.\n");
return;
}
success = state.WriteFile(L"s3-multipart.json");
if (success != true) {
wprintf(L"Upload initiated but saving state failed; recover the upload ID or list unfinished uploads.\n");
return;
}
success = rest.RemoveQueryParam(L"uploads");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.RemoveHeader(L"Content-Type");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.AddQueryParam(L"uploadId",uploadId);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.AddHeader(L"x-amz-copy-source",copySource.getAsString());
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.AddHeader(L"x-amz-copy-source-if-match",sourceEtag);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
CkXmlW parts;
parts.put_Tag(L"CompleteMultipartUpload");
CkStringBuilderW range;
CkStringBuilderW ending;
CkStringBuilderW number;
int partNumber = 1;
while ((partNumber <= numParts)) {
range.Clear();
ending.Clear();
number.Clear();
success = range.Append(L"bytes=");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
if (partNumber == 1) {
success = range.Append(L"0");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
}
else {
success = range.AppendInt(partNumber - 1);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = range.Append(L"000000000");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
}
success = range.Append(L"-");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
if (partNumber <= fullBillions) {
if (partNumber > 1) {
success = ending.AppendInt(partNumber - 1);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
}
success = ending.Append(L"999999999");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
}
else {
success = ending.AppendInt(tailBytes - 1);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
if (fullBillions > 0) {
while ((ending.get_Length() < 9)) {
success = ending.Prepend(L"0");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
}
success = number.AppendInt(fullBillions);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = ending.Prepend(number.getAsString());
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
}
}
success = range.Append(ending.getAsString());
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
number.Clear();
success = number.AppendInt(partNumber);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
if (partNumber > 1) {
success = rest.RemoveQueryParam(L"partNumber");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.RemoveHeader(L"x-amz-copy-source-range");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
}
success = rest.AddQueryParam(L"partNumber",number.getAsString());
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.AddHeader(L"x-amz-copy-source-range",range.getAsString());
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
responseBody = rest.fullRequestNoBody(L"PUT",objectPath.getAsString());
if (rest.get_LastMethodSuccess() != true) {
wprintf(L"Request did not complete; inspect diagnostics privately.\n");
return;
}
if (rest.get_ResponseStatusCode() != 200) {
wprintf(L"S3 HTTP status: %d\n",rest.get_ResponseStatusCode());
success = xml.LoadXml(responseBody);
textCompare.Clear();
textCompare.SetString(xml.tag());
bool sameText11 = textCompare.ContentsEqual(L"Error",true);
if ((success == true) && (sameText11 == true)) {
wprintf(L"S3 error code: %s\n",xml.getChildContent(L"Code"));
}
// 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) {
wprintf(L"Expected well-formed XML.\n");
return;
}
textCompare.Clear();
textCompare.SetString(xml.tag());
bool sameText12 = textCompare.ContentsEqual(L"CopyPartResult",true);
if (sameText12 != true) {
wprintf(L"Unexpected S3 response element; this is not a successful result.\n");
return;
}
textCompare.Clear();
textCompare.SetString(xml.getChildContent(L"ETag"));
bool sameText13 = textCompare.ContentsEqual(L"",true);
if ((xml.HasChildWithTag(L"ETag") != true) || (sameText13 == true)) {
wprintf(L"Missing response field: ETag\n");
return;
}
parts.put_I(partNumber - 1);
parts.UpdateChildContentInt(L"Part[i]|PartNumber",partNumber);
parts.UpdateChildContent(L"Part[i]|ETag",xml.getChildContent(L"ETag"));
wprintf(L"Copied part: %d\n",partNumber);
partNumber = partNumber + 1;
}
success = state.UpdateString(L"completion_xml",parts.getXml());
if (success != true) {
wprintf(L"Could not build saved state.\n");
return;
}
success = state.WriteFile(L"s3-multipart.json");
if (success != true) {
wprintf(L"Parts copied but completion state could not be saved.\n");
return;
}
success = rest.RemoveHeader(L"x-amz-copy-source");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.RemoveHeader(L"x-amz-copy-source-if-match");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.RemoveHeader(L"x-amz-copy-source-range");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.RemoveQueryParam(L"partNumber");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.AddHeader(L"Content-Type",L"application/xml");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
responseBody = rest.fullRequestString(L"POST",objectPath.getAsString(),parts.getXml());
if (rest.get_LastMethodSuccess() != true) {
wprintf(L"Request did not complete; inspect diagnostics privately.\n");
return;
}
if (rest.get_ResponseStatusCode() != 200) {
wprintf(L"S3 HTTP status: %d\n",rest.get_ResponseStatusCode());
success = xml.LoadXml(responseBody);
textCompare.Clear();
textCompare.SetString(xml.tag());
bool sameText14 = textCompare.ContentsEqual(L"Error",true);
if ((success == true) && (sameText14 == true)) {
wprintf(L"S3 error code: %s\n",xml.getChildContent(L"Code"));
}
// 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) {
wprintf(L"Expected well-formed XML.\n");
return;
}
textCompare.Clear();
textCompare.SetString(xml.tag());
bool sameText15 = textCompare.ContentsEqual(L"CompleteMultipartUploadResult",true);
if (sameText15 != true) {
wprintf(L"Unexpected S3 response element; this is not a successful result.\n");
return;
}
textCompare.Clear();
textCompare.SetString(xml.getChildContent(L"ETag"));
bool sameText16 = textCompare.ContentsEqual(L"",true);
if ((xml.HasChildWithTag(L"ETag") != true) || (sameText16 == true)) {
wprintf(L"Missing response field: ETag\n");
return;
}
wprintf(L"Multipart copy completed; source was not deleted.\n");
// Archive s3-multipart.json after confirming the destination.
}