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