Amazon S3: Upload Multipart Parts and Record ETags
See more S3 - REST Examples
Upload an unchanged file in 8 MiB parts and record each exact ETag in ascending part-number order. Requires s3:PutObject. All parts except the last must be at least 5 MiB; use no more than 10,000 parts and choose a larger part size for larger files. This demonstration buffers at most one part for signing rather than the whole file.
Restarting uploads every part again for the same upload ID. It intentionally does not claim durable resumability from a stale local list. Do not run simultaneous writers or change the input file. Prior completion data is invalidated before upload, and a new completion body is saved only after all parts succeed. To implement selective resume, bind state to a file fingerprint and reconcile server parts.
Part of the initiate / upload parts / complete workflow. State in s3-multipart.json binds the upload ID to its bucket, region and key. Keep it private. Incomplete parts incur storage charges until completed or aborted; configure an AbortIncompleteMultipartUpload lifecycle rule as cleanup protection. These examples use the default checksum behavior without selecting a separate composite checksum algorithm. If you choose one at initiation, store each required part checksum and supply it at completion.
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 Lua Downloads
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
local state = chilkat.JsonObject.new()
state.strict = true
success = state:load_file("s3-multipart.json")
if not success then
print("Could not load multipart state.")
return
end
textCompare:clear()
textCompare:set_string(state:string_of("bucket"))
local sameText4 = textCompare:contents_equal("", true)
if (state:json_type_of("bucket") ~= 1) or (sameText4) then
print("Invalid multipart state field: bucket")
return
end
textCompare:clear()
textCompare:set_string(state:string_of("region"))
local sameText5 = textCompare:contents_equal("", true)
if (state:json_type_of("region") ~= 1) or (sameText5) then
print("Invalid multipart state field: region")
return
end
textCompare:clear()
textCompare:set_string(state:string_of("key"))
local sameText6 = textCompare:contents_equal("", true)
if (state:json_type_of("key") ~= 1) or (sameText6) then
print("Invalid multipart state field: key")
return
end
textCompare:clear()
textCompare:set_string(state:string_of("upload_id"))
local sameText7 = textCompare:contents_equal("", true)
if (state:json_type_of("upload_id") ~= 1) or (sameText7) then
print("Invalid multipart state field: upload_id")
return
end
textCompare:clear()
textCompare:set_string(state:string_of("bucket"))
local sameText8 = textCompare:contents_equal(bucketName, true)
textCompare:clear()
textCompare:set_string(state:string_of("region"))
local sameText9 = textCompare:contents_equal(region, true)
if (not sameText8) or (not sameText9) then
print("Multipart state belongs to another bucket or region.")
return
end
local uploadId = state:string_of("upload_id")
-- Supply an unencoded object key, not a URL. Preserve slashes in the key.
local objectKey = state:string_of("key")
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
-- Keep this file unchanged throughout the upload workflow.
local inputFile = "qa_data/files/example.bin"
local partSize = 8388608
local files = chilkat.FileAccess.new()
success = files:open_for_read(inputFile)
if not success then
print("Could not open the input file.")
return
end
local numParts = files:get_num_blocks(partSize)
files:file_close()
if (numParts < 1) or (numParts > 10000) then
print("Choose a larger part size for more than 10000 parts; use PutObject for an empty file.")
return
end
-- Invalidate any prior completion record before changing uploaded parts.
state:delete("completion_xml")
state:delete("part_count")
success = state:write_file("s3-multipart.json")
if not success then
print("Could not invalidate the prior completion record.")
return
end
-- This demonstration uploads EVERY part again if restarted. It never skips a
-- part using an unbound/stale partsList.xml. Re-uploading a part replaces it.
local parts = chilkat.Xml.new()
parts.tag = "CompleteMultipartUpload"
success = parts:add_attribute("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/")
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
local partNumberText = chilkat.StringBuilder.new()
local partNumber = 1
while partNumber <= numParts do
partNumberText:clear()
success = partNumberText: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
end
success = rest:add_query_param("partNumber", partNumberText:get_as_string())
if not success then
print("Could not prepare the request.")
return
end
-- Buffer only this 8 MiB part. Rest authenticates UploadPart with SigV4;
-- this library uses S3's supported UNSIGNED-PAYLOAD mode for this operation.
-- HTTPS protects the transfer; an explicit checksum is a separate option.
local part = chilkat.BinData.new()
success = files:open_for_read(inputFile)
if not success then
print("Could not reopen the unchanged input file.")
return
end
success = files:read_block_bd(partNumber - 1, partSize, part)
files:file_close()
if (not success) or (part.num_bytes == 0) then
print("Could not read the expected part.")
return
end
local partResponse = chilkat.StringBuilder.new()
success = rest:full_request_bd("PUT", objectPath:get_as_string(), part, partResponse)
if not success then
print("Part upload did not complete; inspect diagnostics privately.")
return
end
local responseBody = partResponse:get_as_string()
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 sameText10 = textCompare:contents_equal("Error", true)
if (success) and (sameText10) 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
local etag = rest:response_hdr_by_name("ETag")
textCompare:clear()
textCompare:set_string(etag)
local sameText11 = textCompare:contents_equal("", true)
if (not rest.last_method_success) or (sameText11) then
print("Missing part ETag.")
return
end
parts.i = partNumber - 1
parts:update_child_content_int("Part[i]|PartNumber", partNumber)
parts:update_child_content("Part[i]|ETag", etag)
print("Uploaded part: " .. partNumber)
partNumber = partNumber + 1
end
-- Save only after every part succeeded. Bind the completion body to this state.
success = state:update_string("completion_xml", parts:get_xml())
if not success then
print("Could not prepare the request.")
return
end
success = state:update_int("part_count", numParts)
if not success then
print("Could not prepare the request.")
return
end
success = state:write_file("s3-multipart.json")
if not success then
print("Parts uploaded but state save failed; do not complete with stale state.")
return
end
print("All parts uploaded and completion data saved.")