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 Android™ Downloads
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;
import android.app.Activity;
import com.chilkatsoft.*;
import android.widget.TextView;
import android.os.Bundle;
public class SimpleActivity extends Activity {
private static final String TAG = "Chilkat";
// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean success = false;
// StringBuilder compares text by value in every generated language.
CkStringBuilder textCompare = new CkStringBuilder();
// 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 = new CkJsonObject();
credentials.put_Strict(true);
success = credentials.LoadFile("qa_data/aws/s3.json");
if (success != true) {
Log.i(TAG, "Could not load private AWS credentials.");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.stringOf("access_key"));
boolean sameText1 = textCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("access_key") != 1) or (sameText1 == true)) {
Log.i(TAG, "Missing or invalid access_key.");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.stringOf("secret_key"));
boolean sameText2 = textCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("secret_key") != 1) or (sameText2 == true)) {
Log.i(TAG, "Missing or invalid secret_key.");
return;
}
// General purpose bucket in the commercial AWS partition.
String region = "us-west-2";
String bucketName = "amzn-s3-demo-bucket";
CkStringBuilder endpoint = new CkStringBuilder();
success = endpoint.Append(bucketName);
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
success = endpoint.Append(".");
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
success = endpoint.Append("s3.");
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
success = endpoint.Append(region);
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
success = endpoint.Append(".amazonaws.com");
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
CkAuthAws aws = new CkAuthAws();
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 = new CkRest();
rest.put_ConnectTimeoutMs(20000);
rest.put_IdleTimeoutMs(60000);
success = rest.SetAuthAws(aws);
if (success != true) {
Log.i(TAG, "Could not configure AWS signing.");
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) {
Log.i(TAG, "session_token must be a string.");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.stringOf("session_token"));
boolean sameText3 = textCompare.ContentsEqual("",true);
if (sameText3 != true) {
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"));
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
}
}
// Connect to the SAME hostname used for TLS verification and request signing.
CkSocket connection = new CkSocket();
connection.put_RequireSslCertVerify(true);
connection.put_MaxReadIdleMs(60000);
connection.put_MaxSendIdleMs(60000);
success = connection.Connect(endpoint.getAsString(),443,true,20000);
if (success != true) {
Log.i(TAG, "TLS connection failed; inspect diagnostics privately.");
return;
}
success = rest.UseConnection(connection,true);
if (success != true) {
Log.i(TAG, "Could not attach the TLS connection.");
return;
}
CkXml xml = new CkXml();
xml.put_Strict(true);
// Supply an unencoded object key, not a URL. Preserve slashes in the key.
String objectKey = "documents/source.bin";
CkStringBuilder objectPath = new CkStringBuilder();
success = objectPath.Append(objectKey);
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
success = objectPath.Encode("url_rfc3986","utf-8");
if (success != true) {
Log.i(TAG, "Could not encode the object key.");
return;
}
int restoredSlashes = objectPath.Replace("%2F","/");
success = objectPath.Prepend("/");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.SendReqNoBody("HEAD",objectPath.getAsString());
if (success != true) {
Log.i(TAG, "Could not send HEAD request.");
return;
}
int statusCode = rest.ReadResponseHeader();
if (statusCode < 0) {
Log.i(TAG, "Could not read the response header.");
return;
}
if (statusCode != 200) {
Log.i(TAG, "HEAD did not return HTTP 200. A 403 is not proof that an object is missing.");
return;
}
// HEAD has no response body; do not call a body-reading method.
String sourceEtag = rest.responseHdrByName("ETag");
textCompare.Clear();
textCompare.SetString(sourceEtag);
boolean sameText4 = textCompare.ContentsEqual("",true);
if ((rest.get_LastMethodSuccess() != true) or (sameText4 == true)) {
Log.i(TAG, "Missing response header: ETag");
return;
}
String sourceSize = rest.responseHdrByName("Content-Length");
textCompare.Clear();
textCompare.SetString(sourceSize);
boolean sameText5 = textCompare.ContentsEqual("",true);
if ((rest.get_LastMethodSuccess() != true) or (sameText5 == true)) {
Log.i(TAG, "Missing response header: Content-Length");
return;
}
String 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 = new CkStringBuilder();
CkStringBuilder digits = new CkStringBuilder();
CkStringBuilder piece = new CkStringBuilder();
success = sizeText.Append(sourceSize);
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
success = digits.Append("0123456789");
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
if ((sizeText.get_Length() < 1) or (sizeText.get_Length() > 14)) {
Log.i(TAG, "Invalid source length for this example.");
return;
}
int position = 0;
while ((position < sizeText.get_Length())) {
String digit = sizeText.getRange(position,1,false);
if (digits.Contains(digit,true) != true) {
Log.i(TAG, "Source length is not decimal.");
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) {
Log.i(TAG, "Could not prepare the request.");
return;
}
fullBillions = piece.get_IntValue();
success = piece.SetString(sizeText.getRange(sizeText.get_Length() - 9,9,false));
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
tailBytes = piece.get_IntValue();
}
else {
tailBytes = sizeText.get_IntValue();
}
int numParts = fullBillions;
if (tailBytes > 0) {
numParts = numParts + 1;
}
if ((numParts < 1) or (numParts > 10000)) {
Log.i(TAG, "This example supports objects through 10 TB using 1 GB parts.");
return;
}
if ((fullBillions == 0) and (tailBytes <= 5242880)) {
Log.i(TAG, "Use CopyObject for sources of 5 MiB or less; ranged copy requires a larger source.");
return;
}
CkFileAccess files = new CkFileAccess();
if (files.FileExists("s3-multipart.json") == true) {
Log.i(TAG, "A multipart state file already exists; finish or abort that upload first.");
return;
}
CkStringBuilder copySource = new CkStringBuilder();
success = copySource.Append("/");
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
success = copySource.Append(bucketName);
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
success = copySource.Append(objectPath.getAsString());
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
textCompare.Clear();
textCompare.SetString(sourceVersion);
boolean sameText6 = textCompare.ContentsEqual("",true);
if (sameText6 != true) {
CkStringBuilder encodedVersion = new CkStringBuilder();
success = encodedVersion.Append(sourceVersion);
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
success = encodedVersion.Encode("url_rfc3986","utf-8");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = copySource.Append("?versionId=");
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
success = copySource.Append(encodedVersion.getAsString());
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
}
// Destination is a DIFFERENT key in this bucket. Existing destination is replaced.
String destinationKey = "documents/copy.bin";
textCompare.Clear();
textCompare.SetString(destinationKey);
boolean sameText7 = textCompare.ContentsEqual(objectKey,true);
if (sameText7 == true) {
Log.i(TAG, "Choose a destination key different from the source.");
return;
}
success = objectPath.SetString(destinationKey);
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = objectPath.Encode("url_rfc3986","utf-8");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
int destinationSlashes = objectPath.Replace("%2F","/");
success = objectPath.Prepend("/");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.AddQueryParam("uploads","");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.AddHeader("Content-Type","application/octet-stream");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
String responseBody = rest.fullRequestNoBody("POST",objectPath.getAsString());
if (rest.get_LastMethodSuccess() != true) {
Log.i(TAG, "Request did not complete; inspect diagnostics privately.");
return;
}
if (rest.get_ResponseStatusCode() != 200) {
Log.i(TAG, "S3 HTTP status: " + String.valueOf(rest.get_ResponseStatusCode()));
success = xml.LoadXml(responseBody);
textCompare.Clear();
textCompare.SetString(xml.tag());
boolean sameText8 = textCompare.ContentsEqual("Error",true);
if ((success == true) and (sameText8 == true)) {
Log.i(TAG, "S3 error code: " + xml.getChildContent("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) {
Log.i(TAG, "Expected well-formed XML.");
return;
}
textCompare.Clear();
textCompare.SetString(xml.tag());
boolean sameText9 = textCompare.ContentsEqual("InitiateMultipartUploadResult",true);
if (sameText9 != true) {
Log.i(TAG, "Unexpected S3 response element; this is not a successful result.");
return;
}
textCompare.Clear();
textCompare.SetString(xml.getChildContent("UploadId"));
boolean sameText10 = textCompare.ContentsEqual("",true);
if ((xml.HasChildWithTag("UploadId") != true) or (sameText10 == true)) {
Log.i(TAG, "Missing response field: UploadId");
return;
}
String uploadId = xml.getChildContent("UploadId");
CkJsonObject state = new CkJsonObject();
success = state.UpdateString("bucket",bucketName);
if (success != true) {
Log.i(TAG, "Could not build saved state.");
return;
}
success = state.UpdateString("region",region);
if (success != true) {
Log.i(TAG, "Could not build saved state.");
return;
}
success = state.UpdateString("key",destinationKey);
if (success != true) {
Log.i(TAG, "Could not build saved state.");
return;
}
success = state.UpdateString("upload_id",uploadId);
if (success != true) {
Log.i(TAG, "Could not build saved state.");
return;
}
success = state.UpdateString("source_key",objectKey);
if (success != true) {
Log.i(TAG, "Could not build saved state.");
return;
}
success = state.UpdateString("source_etag",sourceEtag);
if (success != true) {
Log.i(TAG, "Could not build saved state.");
return;
}
success = state.UpdateString("source_size",sourceSize);
if (success != true) {
Log.i(TAG, "Could not build saved state.");
return;
}
success = state.WriteFile("s3-multipart.json");
if (success != true) {
Log.i(TAG, "Upload initiated but saving state failed; recover the upload ID or list unfinished uploads.");
return;
}
success = rest.RemoveQueryParam("uploads");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.RemoveHeader("Content-Type");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.AddQueryParam("uploadId",uploadId);
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.AddHeader("x-amz-copy-source",copySource.getAsString());
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.AddHeader("x-amz-copy-source-if-match",sourceEtag);
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
CkXml parts = new CkXml();
parts.put_Tag("CompleteMultipartUpload");
CkStringBuilder range = new CkStringBuilder();
CkStringBuilder ending = new CkStringBuilder();
CkStringBuilder number = new CkStringBuilder();
int partNumber = 1;
while ((partNumber <= numParts)) {
range.Clear();
ending.Clear();
number.Clear();
success = range.Append("bytes=");
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
if (partNumber == 1) {
success = range.Append("0");
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
}
else {
success = range.AppendInt(partNumber - 1);
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = range.Append("000000000");
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
}
success = range.Append("-");
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
if (partNumber <= fullBillions) {
if (partNumber > 1) {
success = ending.AppendInt(partNumber - 1);
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
}
success = ending.Append("999999999");
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
}
else {
success = ending.AppendInt(tailBytes - 1);
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
if (fullBillions > 0) {
while ((ending.get_Length() < 9)) {
success = ending.Prepend("0");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
}
success = number.AppendInt(fullBillions);
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = ending.Prepend(number.getAsString());
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
}
}
success = range.Append(ending.getAsString());
if (success != true) {
Log.i(TAG, "Could not build text.");
return;
}
number.Clear();
success = number.AppendInt(partNumber);
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
if (partNumber > 1) {
success = rest.RemoveQueryParam("partNumber");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.RemoveHeader("x-amz-copy-source-range");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
}
success = rest.AddQueryParam("partNumber",number.getAsString());
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.AddHeader("x-amz-copy-source-range",range.getAsString());
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
responseBody = rest.fullRequestNoBody("PUT",objectPath.getAsString());
if (rest.get_LastMethodSuccess() != true) {
Log.i(TAG, "Request did not complete; inspect diagnostics privately.");
return;
}
if (rest.get_ResponseStatusCode() != 200) {
Log.i(TAG, "S3 HTTP status: " + String.valueOf(rest.get_ResponseStatusCode()));
success = xml.LoadXml(responseBody);
textCompare.Clear();
textCompare.SetString(xml.tag());
boolean sameText11 = textCompare.ContentsEqual("Error",true);
if ((success == true) and (sameText11 == true)) {
Log.i(TAG, "S3 error code: " + xml.getChildContent("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) {
Log.i(TAG, "Expected well-formed XML.");
return;
}
textCompare.Clear();
textCompare.SetString(xml.tag());
boolean sameText12 = textCompare.ContentsEqual("CopyPartResult",true);
if (sameText12 != true) {
Log.i(TAG, "Unexpected S3 response element; this is not a successful result.");
return;
}
textCompare.Clear();
textCompare.SetString(xml.getChildContent("ETag"));
boolean sameText13 = textCompare.ContentsEqual("",true);
if ((xml.HasChildWithTag("ETag") != true) or (sameText13 == true)) {
Log.i(TAG, "Missing response field: ETag");
return;
}
parts.put_I(partNumber - 1);
parts.UpdateChildContentInt("Part[i]|PartNumber",partNumber);
parts.UpdateChildContent("Part[i]|ETag",xml.getChildContent("ETag"));
Log.i(TAG, "Copied part: " + String.valueOf(partNumber));
partNumber = partNumber + 1;
}
success = state.UpdateString("completion_xml",parts.getXml());
if (success != true) {
Log.i(TAG, "Could not build saved state.");
return;
}
success = state.WriteFile("s3-multipart.json");
if (success != true) {
Log.i(TAG, "Parts copied but completion state could not be saved.");
return;
}
success = rest.RemoveHeader("x-amz-copy-source");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.RemoveHeader("x-amz-copy-source-if-match");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.RemoveHeader("x-amz-copy-source-range");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.RemoveQueryParam("partNumber");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
success = rest.AddHeader("Content-Type","application/xml");
if (success != true) {
Log.i(TAG, "Could not prepare the request.");
return;
}
responseBody = rest.fullRequestString("POST",objectPath.getAsString(),parts.getXml());
if (rest.get_LastMethodSuccess() != true) {
Log.i(TAG, "Request did not complete; inspect diagnostics privately.");
return;
}
if (rest.get_ResponseStatusCode() != 200) {
Log.i(TAG, "S3 HTTP status: " + String.valueOf(rest.get_ResponseStatusCode()));
success = xml.LoadXml(responseBody);
textCompare.Clear();
textCompare.SetString(xml.tag());
boolean sameText14 = textCompare.ContentsEqual("Error",true);
if ((success == true) and (sameText14 == true)) {
Log.i(TAG, "S3 error code: " + xml.getChildContent("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) {
Log.i(TAG, "Expected well-formed XML.");
return;
}
textCompare.Clear();
textCompare.SetString(xml.tag());
boolean sameText15 = textCompare.ContentsEqual("CompleteMultipartUploadResult",true);
if (sameText15 != true) {
Log.i(TAG, "Unexpected S3 response element; this is not a successful result.");
return;
}
textCompare.Clear();
textCompare.SetString(xml.getChildContent("ETag"));
boolean sameText16 = textCompare.ContentsEqual("",true);
if ((xml.HasChildWithTag("ETag") != true) or (sameText16 == true)) {
Log.i(TAG, "Missing response field: ETag");
return;
}
Log.i(TAG, "Multipart copy completed; source was not deleted.");
// Archive s3-multipart.json after confirming the destination.
}
static {
System.loadLibrary("chilkat");
// Note: If the incorrect library name is passed to System.loadLibrary,
// then you will see the following error message at application startup:
//"The application <your-application-name> has stopped unexpectedly. Please try again."
}
}