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

Amazon S3: Resume a Download with Range and If-Match

See more S3 - REST Examples

Resume an unchanged partial file using its original quoted ETag and total length, not metadata fetched after the failure. Save a private s3-download.json sidecar when starting: string fields bucket, key, region, etag (including quotes), and total_size. Use s3-download.part for that object only.

FileSizeStr avoids 32-bit overflow. The code appends only HTTP 206 with a matching ETag, Content-Range start and total size. A 200 response must never be appended; 412 means the validator failed, and 416 is not automatically success. Check final size, and verify an independently recorded checksum when needed. ETags are validators, not universally MD5 hashes. Concurrent local modification is outside this example.

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 GetObject 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/example.txt"
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

-- The sidecar must describe the SAME partial file and original object.
-- Save its exact quoted ETag and full Content-Length when starting the download.
local checkpoint = chilkat.JsonObject.new()
checkpoint.strict = true
success = checkpoint:load_file("s3-download.json")
if not success then
    print("Could not load the download checkpoint.")
    return
end

textCompare:clear()
textCompare:set_string(checkpoint:string_of("bucket"))
local sameText4 = textCompare:contents_equal("", true)
if (checkpoint:json_type_of("bucket") ~= 1) or (sameText4) then
    print("Invalid checkpoint field: bucket")
    return
end

textCompare:clear()
textCompare:set_string(checkpoint:string_of("key"))
local sameText5 = textCompare:contents_equal("", true)
if (checkpoint:json_type_of("key") ~= 1) or (sameText5) then
    print("Invalid checkpoint field: key")
    return
end

textCompare:clear()
textCompare:set_string(checkpoint:string_of("region"))
local sameText6 = textCompare:contents_equal("", true)
if (checkpoint:json_type_of("region") ~= 1) or (sameText6) then
    print("Invalid checkpoint field: region")
    return
end

textCompare:clear()
textCompare:set_string(checkpoint:string_of("etag"))
local sameText7 = textCompare:contents_equal("", true)
if (checkpoint:json_type_of("etag") ~= 1) or (sameText7) then
    print("Invalid checkpoint field: etag")
    return
end

textCompare:clear()
textCompare:set_string(checkpoint:string_of("total_size"))
local sameText8 = textCompare:contents_equal("", true)
if (checkpoint:json_type_of("total_size") ~= 1) or (sameText8) then
    print("Invalid checkpoint field: total_size")
    return
end

textCompare:clear()
textCompare:set_string(checkpoint:string_of("bucket"))
local sameText9 = textCompare:contents_equal(bucketName, true)
textCompare:clear()
textCompare:set_string(checkpoint:string_of("key"))
local sameText10 = textCompare:contents_equal(objectKey, true)
textCompare:clear()
textCompare:set_string(checkpoint:string_of("region"))
local sameText11 = textCompare:contents_equal(region, true)
if (not sameText9) or ((not sameText10) or (not sameText11)) then
    print("Checkpoint does not match this object.")
    return
end

local files = chilkat.FileAccess.new()
local localSize = files:file_size_str("s3-download.part")
if not files.last_method_success then
    print("Could not determine the partial file size.")
    return
end

textCompare:clear()
textCompare:set_string(localSize)
local sameText12 = textCompare:contents_equal(checkpoint:string_of("total_size"), true)
if sameText12 then
    print("Local length already matches the checkpoint; verify integrity before publishing.")
    return
end

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

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

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

success = rest:add_header("Range", range:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("If-Match", checkpoint:string_of("etag"))
if not success then
    print("Could not prepare the request.")
    return
end

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

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

if statusCode ~= 206 then
    print("Download HTTP status: " .. statusCode)
    local errorBody = rest:read_resp_body_string()
    if rest.last_method_success then
        success = xml:load_xml(errorBody)
        textCompare:clear()
        textCompare:set_string(xml.tag)
        local sameText13 = textCompare:contents_equal("Error", true)
        if (success) and (sameText13) then
            print("S3 error code: " .. xml:get_child_content("Code"))
        end
    end

    return
end

-- Never append HTTP 200, 412, or 416 to the existing file.
local returnedEtag = rest:response_hdr_by_name("ETag")
textCompare:clear()
textCompare:set_string(returnedEtag)
local sameText14 = textCompare:contents_equal(checkpoint:string_of("etag"), true)
if (not rest.last_method_success) or (not sameText14) then
    print("Object validator changed; partial file was not modified.")
    return
end

local contentRange = chilkat.StringBuilder.new()
success = contentRange:append(rest:response_hdr_by_name("Content-Range"))
if not success then
    print("Could not prepare the request.")
    return
end

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

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

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

if not contentRange:starts_with(expectedStart:get_as_string(), true) then
    print("Range start does not match the partial file.")
    return
end

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

success = expectedTotal:append(checkpoint:string_of("total_size"))
if not success then
    print("Could not build text.")
    return
end

if not contentRange:ends_with(expectedTotal:get_as_string(), true) then
    print("Object length changed; partial file was not modified.")
    return
end

-- The file must be an unchanged prefix of the object; size alone cannot prove that.
local output = chilkat.Stream.new()
output.sink_file = "s3-download.part"
output.sink_file_append = true
success = rest:read_resp_body_stream(output, true)
if not success then
    print("Resume incomplete; retain the partial file and original checkpoint.")
    return
end

local finalSize = files:file_size_str("s3-download.part")
textCompare:clear()
textCompare:set_string(finalSize)
local sameText15 = textCompare:contents_equal(checkpoint:string_of("total_size"), true)
if (not files.last_method_success) or (not sameText15) then
    print("Result length does not match the original full object.")
    return
end

print("Resumed download complete.")