Sample code for 30+ languages & platforms
Lua 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 Lua Downloads

Lua
local chilkat = require("chilkat")

-- StringBuilder compares text by value in every generated language.
local textCompare = chilkat.StringBuilder.new()
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- Private configuration, not a file in public web content or source control.
-- Load current IAM credentials authorized for the S3 operation.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
success = credentials:load_file("qa_data/aws/s3.json")
if not success then
    print("Could not load private AWS credentials.")
    return
end

textCompare:clear()
textCompare:set_string(credentials:string_of("access_key"))
local sameText1 = textCompare:contents_equal("", true)
if (credentials:json_type_of("access_key") ~= 1) or (sameText1) then
    print("Missing or invalid access_key.")
    return
end

textCompare:clear()
textCompare:set_string(credentials:string_of("secret_key"))
local sameText2 = textCompare:contents_equal("", true)
if (credentials:json_type_of("secret_key") ~= 1) or (sameText2) then
    print("Missing or invalid secret_key.")
    return
end

-- General purpose bucket in the commercial AWS partition.
local region = "us-west-2"
local bucketName = "amzn-s3-demo-bucket"
local endpoint = chilkat.StringBuilder.new()
success = endpoint:append(bucketName)
if not success then
    print("Could not build text.")
    return
end

success = endpoint:append(".")
if not success then
    print("Could not build text.")
    return
end

success = endpoint:append("s3.")
if not success then
    print("Could not build text.")
    return
end

success = endpoint:append(region)
if not success then
    print("Could not build text.")
    return
end

success = endpoint:append(".amazonaws.com")
if not success then
    print("Could not build text.")
    return
end

local aws = chilkat.AuthAws.new()
aws.access_key = credentials:string_of("access_key")
aws.secret_key = credentials:string_of("secret_key")
aws.region = region
aws.service_name = "s3"
aws.signature_version = 4
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
success = rest:set_auth_aws(aws)
if not success then
    print("Could not configure AWS signing.")
    return
end

-- Temporary credentials require this token in every signed query.
-- Keep request URLs private. Do not clear this parameter between requests.
if credentials:has_member("session_token") then
    if credentials:json_type_of("session_token") ~= 1 then
        print("session_token must be a string.")
        return
    end

    textCompare:clear()
    textCompare:set_string(credentials:string_of("session_token"))
    local sameText3 = textCompare:contents_equal("", true)
    if not sameText3 then
        success = rest:add_query_param("X-Amz-Security-Token", credentials:string_of("session_token"))
        if not success then
            print("Could not prepare the request.")
            return
        end
    end
end

-- Connect to the SAME hostname used for TLS verification and request signing.
local connection = chilkat.Socket.new()
connection.require_ssl_cert_verify = true
connection.max_read_idle_ms = 60000
connection.max_send_idle_ms = 60000
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
    print("TLS connection failed; inspect diagnostics privately.")
    return
end

success = rest:use_connection(connection, true)
if not success then
    print("Could not attach the TLS connection.")
    return
end

local xml = chilkat.Xml.new()
xml.strict = true
-- Supply an unencoded object key, not a URL. Preserve slashes in the key.
local objectKey = "documents/source.bin"
local objectPath = chilkat.StringBuilder.new()
success = objectPath:append(objectKey)
if not success then
    print("Could not build text.")
    return
end

success = objectPath:encode("url_rfc3986", "utf-8")
if not success then
    print("Could not encode the object key.")
    return
end

local restoredSlashes = objectPath:replace("%2F", "/")
success = objectPath:prepend("/")
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:send_req_no_body("HEAD", objectPath:get_as_string())
if not success then
    print("Could not send HEAD request.")
    return
end

local statusCode = rest:read_response_header()
if statusCode < 0 then
    print("Could not read the response header.")
    return
end

if statusCode ~= 200 then
    print("HEAD did not return HTTP 200. A 403 is not proof that an object is missing.")
    return
end

-- HEAD has no response body; do not call a body-reading method.
local sourceEtag = rest:response_hdr_by_name("ETag")
textCompare:clear()
textCompare:set_string(sourceEtag)
local sameText4 = textCompare:contents_equal("", true)
if (not rest.last_method_success) or (sameText4) then
    print("Missing response header: ETag")
    return
end

local sourceSize = rest:response_hdr_by_name("Content-Length")
textCompare:clear()
textCompare:set_string(sourceSize)
local sameText5 = textCompare:contents_equal("", true)
if (not rest.last_method_success) or (sameText5) then
    print("Missing response header: Content-Length")
    return
end

local sourceVersion = rest:response_hdr_by_name("x-amz-version-id")
if not rest.last_method_success then
    sourceVersion = ""
end

-- Split a decimal size into billions and a remainder. No large integer type.
local sizeText = chilkat.StringBuilder.new()
local digits = chilkat.StringBuilder.new()
local piece = chilkat.StringBuilder.new()
success = sizeText:append(sourceSize)
if not success then
    print("Could not build text.")
    return
end

success = digits:append("0123456789")
if not success then
    print("Could not build text.")
    return
end

if (sizeText.length < 1) or (sizeText.length > 14) then
    print("Invalid source length for this example.")
    return
end

local position = 0
while position < sizeText.length do
    local digit = sizeText:get_range(position, 1, false)
    if not digits:contains(digit, true) then
        print("Source length is not decimal.")
        return
    end

    position = position + 1
end

local fullBillions = 0
local tailBytes = 0
if sizeText.length > 9 then
    success = piece:set_string(sizeText:get_range(0, sizeText.length - 9, false))
    if not success then
        print("Could not prepare the request.")
        return
    end

    fullBillions = piece.int_value
    success = piece:set_string(sizeText:get_range(sizeText.length - 9, 9, false))
    if not success then
        print("Could not prepare the request.")
        return
    end

    tailBytes = piece.int_value
else
    tailBytes = sizeText.int_value
end

local numParts = fullBillions
if tailBytes > 0 then
    numParts = numParts + 1
end

if (numParts < 1) or (numParts > 10000) then
    print("This example supports objects through 10 TB using 1 GB parts.")
    return
end

if (fullBillions == 0) and (tailBytes <= 5242880) then
    print("Use CopyObject for sources of 5 MiB or less; ranged copy requires a larger source.")
    return
end

local files = chilkat.FileAccess.new()
if files:file_exists("s3-multipart.json") then
    print("A multipart state file already exists; finish or abort that upload first.")
    return
end

local copySource = chilkat.StringBuilder.new()
success = copySource:append("/")
if not success then
    print("Could not build text.")
    return
end

success = copySource:append(bucketName)
if not success then
    print("Could not build text.")
    return
end

success = copySource:append(objectPath:get_as_string())
if not success then
    print("Could not build text.")
    return
end

textCompare:clear()
textCompare:set_string(sourceVersion)
local sameText6 = textCompare:contents_equal("", true)
if not sameText6 then
    local encodedVersion = chilkat.StringBuilder.new()
    success = encodedVersion:append(sourceVersion)
    if not success then
        print("Could not build text.")
        return
    end

    success = encodedVersion:encode("url_rfc3986", "utf-8")
    if not success then
        print("Could not prepare the request.")
        return
    end

    success = copySource:append("?versionId=")
    if not success then
        print("Could not build text.")
        return
    end

    success = copySource:append(encodedVersion:get_as_string())
    if not success then
        print("Could not build text.")
        return
    end
end

-- Destination is a DIFFERENT key in this bucket. Existing destination is replaced.
local destinationKey = "documents/copy.bin"
textCompare:clear()
textCompare:set_string(destinationKey)
local sameText7 = textCompare:contents_equal(objectKey, true)
if sameText7 then
    print("Choose a destination key different from the source.")
    return
end

success = objectPath:set_string(destinationKey)
if not success then
    print("Could not prepare the request.")
    return
end

success = objectPath:encode("url_rfc3986", "utf-8")
if not success then
    print("Could not prepare the request.")
    return
end

local destinationSlashes = objectPath:replace("%2F", "/")
success = objectPath:prepend("/")
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_query_param("uploads", "")
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("Content-Type", "application/octet-stream")
if not success then
    print("Could not prepare the request.")
    return
end

local responseBody = rest:full_request_no_body("POST", objectPath:get_as_string())
if not rest.last_method_success then
    print("Request did not complete; inspect diagnostics privately.")
    return
end

if rest.response_status_code ~= 200 then
    print("S3 HTTP status: " .. rest.response_status_code)
    success = xml:load_xml(responseBody)
    textCompare:clear()
    textCompare:set_string(xml.tag)
    local sameText8 = textCompare:contents_equal("Error", true)
    if (success) and (sameText8) then
        print("S3 error code: " .. xml:get_child_content("Code"))
    end

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

success = xml:load_xml(responseBody)
if not success then
    print("Expected well-formed XML.")
    return
end

textCompare:clear()
textCompare:set_string(xml.tag)
local sameText9 = textCompare:contents_equal("InitiateMultipartUploadResult", true)
if not sameText9 then
    print("Unexpected S3 response element; this is not a successful result.")
    return
end

textCompare:clear()
textCompare:set_string(xml:get_child_content("UploadId"))
local sameText10 = textCompare:contents_equal("", true)
if (not xml:has_child_with_tag("UploadId")) or (sameText10) then
    print("Missing response field: UploadId")
    return
end

local uploadId = xml:get_child_content("UploadId")
local state = chilkat.JsonObject.new()
success = state:update_string("bucket", bucketName)
if not success then
    print("Could not build saved state.")
    return
end

success = state:update_string("region", region)
if not success then
    print("Could not build saved state.")
    return
end

success = state:update_string("key", destinationKey)
if not success then
    print("Could not build saved state.")
    return
end

success = state:update_string("upload_id", uploadId)
if not success then
    print("Could not build saved state.")
    return
end

success = state:update_string("source_key", objectKey)
if not success then
    print("Could not build saved state.")
    return
end

success = state:update_string("source_etag", sourceEtag)
if not success then
    print("Could not build saved state.")
    return
end

success = state:update_string("source_size", sourceSize)
if not success then
    print("Could not build saved state.")
    return
end

success = state:write_file("s3-multipart.json")
if not success then
    print("Upload initiated but saving state failed; recover the upload ID or list unfinished uploads.")
    return
end

success = rest:remove_query_param("uploads")
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:remove_header("Content-Type")
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_query_param("uploadId", uploadId)
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("x-amz-copy-source", copySource:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("x-amz-copy-source-if-match", sourceEtag)
if not success then
    print("Could not prepare the request.")
    return
end

local parts = chilkat.Xml.new()
parts.tag = "CompleteMultipartUpload"
local range = chilkat.StringBuilder.new()
local ending = chilkat.StringBuilder.new()
local number = chilkat.StringBuilder.new()
local partNumber = 1
while partNumber <= numParts do
    range:clear()
    ending:clear()
    number:clear()
    success = range:append("bytes=")
    if not success then
        print("Could not build text.")
        return
    end

    if partNumber == 1 then
        success = range:append("0")
        if not success then
            print("Could not build text.")
            return
        end
    else
        success = range:append_int(partNumber - 1)
        if not success then
            print("Could not prepare the request.")
            return
        end

        success = range:append("000000000")
        if not success then
            print("Could not build text.")
            return
        end
    end

    success = range:append("-")
    if not success then
        print("Could not build text.")
        return
    end

    if partNumber <= fullBillions then
        if partNumber > 1 then
            success = ending:append_int(partNumber - 1)
            if not success then
                print("Could not prepare the request.")
                return
            end
        end

        success = ending:append("999999999")
        if not success then
            print("Could not build text.")
            return
        end
    else
        success = ending:append_int(tailBytes - 1)
        if not success then
            print("Could not prepare the request.")
            return
        end

        if fullBillions > 0 then
            while ending.length < 9 do
                success = ending:prepend("0")
                if not success then
                    print("Could not prepare the request.")
                    return
                end
            end

            success = number:append_int(fullBillions)
            if not success then
                print("Could not prepare the request.")
                return
            end

            success = ending:prepend(number:get_as_string())
            if not success then
                print("Could not prepare the request.")
                return
            end
        end
    end

    success = range:append(ending:get_as_string())
    if not success then
        print("Could not build text.")
        return
    end

    number:clear()
    success = number:append_int(partNumber)
    if not success then
        print("Could not prepare the request.")
        return
    end

    if partNumber > 1 then
        success = rest:remove_query_param("partNumber")
        if not success then
            print("Could not prepare the request.")
            return
        end

        success = rest:remove_header("x-amz-copy-source-range")
        if not success then
            print("Could not prepare the request.")
            return
        end
    end

    success = rest:add_query_param("partNumber", number:get_as_string())
    if not success then
        print("Could not prepare the request.")
        return
    end

    success = rest:add_header("x-amz-copy-source-range", range:get_as_string())
    if not success then
        print("Could not prepare the request.")
        return
    end

    responseBody = rest:full_request_no_body("PUT", objectPath:get_as_string())
    if not rest.last_method_success then
        print("Request did not complete; inspect diagnostics privately.")
        return
    end

    if rest.response_status_code ~= 200 then
        print("S3 HTTP status: " .. rest.response_status_code)
        success = xml:load_xml(responseBody)
        textCompare:clear()
        textCompare:set_string(xml.tag)
        local sameText11 = textCompare:contents_equal("Error", true)
        if (success) and (sameText11) then
            print("S3 error code: " .. xml:get_child_content("Code"))
        end

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

    success = xml:load_xml(responseBody)
    if not success then
        print("Expected well-formed XML.")
        return
    end

    textCompare:clear()
    textCompare:set_string(xml.tag)
    local sameText12 = textCompare:contents_equal("CopyPartResult", true)
    if not sameText12 then
        print("Unexpected S3 response element; this is not a successful result.")
        return
    end

    textCompare:clear()
    textCompare:set_string(xml:get_child_content("ETag"))
    local sameText13 = textCompare:contents_equal("", true)
    if (not xml:has_child_with_tag("ETag")) or (sameText13) then
        print("Missing response field: ETag")
        return
    end

    parts.i = partNumber - 1
    parts:update_child_content_int("Part[i]|PartNumber", partNumber)
    parts:update_child_content("Part[i]|ETag", xml:get_child_content("ETag"))
    print("Copied part: " .. partNumber)
    partNumber = partNumber + 1
end

success = state:update_string("completion_xml", parts:get_xml())
if not success then
    print("Could not build saved state.")
    return
end

success = state:write_file("s3-multipart.json")
if not success then
    print("Parts copied but completion state could not be saved.")
    return
end

success = rest:remove_header("x-amz-copy-source")
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:remove_header("x-amz-copy-source-if-match")
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:remove_header("x-amz-copy-source-range")
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:remove_query_param("partNumber")
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("Content-Type", "application/xml")
if not success then
    print("Could not prepare the request.")
    return
end

responseBody = rest:full_request_string("POST", objectPath:get_as_string(), parts:get_xml())
if not rest.last_method_success then
    print("Request did not complete; inspect diagnostics privately.")
    return
end

if rest.response_status_code ~= 200 then
    print("S3 HTTP status: " .. rest.response_status_code)
    success = xml:load_xml(responseBody)
    textCompare:clear()
    textCompare:set_string(xml.tag)
    local sameText14 = textCompare:contents_equal("Error", true)
    if (success) and (sameText14) then
        print("S3 error code: " .. xml:get_child_content("Code"))
    end

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

success = xml:load_xml(responseBody)
if not success then
    print("Expected well-formed XML.")
    return
end

textCompare:clear()
textCompare:set_string(xml.tag)
local sameText15 = textCompare:contents_equal("CompleteMultipartUploadResult", true)
if not sameText15 then
    print("Unexpected S3 response element; this is not a successful result.")
    return
end

textCompare:clear()
textCompare:set_string(xml:get_child_content("ETag"))
local sameText16 = textCompare:contents_equal("", true)
if (not xml:has_child_with_tag("ETag")) or (sameText16) then
    print("Missing response field: ETag")
    return
end

print("Multipart copy completed; source was not deleted.")
-- Archive s3-multipart.json after confirming the destination.