Azure Blob: Resume a Download with ETag Protection
See more Azure Cloud Storage Examples
Save the account, path, ETag and size in an immutable checkpoint, then append complete byte ranges to a private .part file. A later run uses the existing partial-file length as its offset and checks that HEAD still describes the same blob. Every range carries If-Match and must return the expected ETag, exact Content-Range, Content-Length and body size before any bytes are appended.
The demonstration bounds offsets to 2,000,000,000 bytes so it can use int arithmetic without overflow; this is not an Azure service limit. Sizes in checkpoints remain strings. Only the final successful transfer renames the partial output to the final filename. Empty blobs are handled without issuing an invalid range.
Use one process, an exclusive local destination and an unchanged partial file. The checkpoint does not independently hash or authenticate local content; do not point it at an unrelated file or reuse a partial file that was edited or suffered disk corruption. After a local write failure inspect or restart the partial file. On 412 or changed HEAD properties, preserve the previous partial output and start a new download separately instead of combining versions. A crash while initially publishing the checkpoint fails closed if state is incomplete.
Uses direct Chilkat.Rest requests and Azure public-cloud endpoints with verified HTTPS. REST requests select service version 2026-04-06. Create local input/output directories before running. Account-key examples read account and access_key string fields from private qa_data/azure/storage.json; do not embed secrets in distributed applications. Entra examples explain their own configuration. Keep credentials, bearer tokens, SAS URLs and diagnostic dumps private. Shared Key is supported only where allowed by account policy; Entra authentication is preferred where available.
Transport success and HTTP status are checked separately. Writes are not automatically replayed after an uncertain response. IDs, ETags, continuation markers and file sizes are strings; counters and explicitly bounded offsets use int. No webhook or web server is required.
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
local config = chilkat.JsonObject.new()
config.strict = true
success = config:load_file("qa_data/azure/storage.json")
if not success then
print("Could not load private Azure configuration.")
return
end
textCompare:clear()
textCompare:set_string(config:string_of("account"))
local sameText1 = textCompare:contents_equal("", true)
if (config:json_type_of("account") ~= 1) or (sameText1) then
print("Supply the storage account name.")
return
end
-- access_key is the base64 account key, not a connection string or SAS.
textCompare:clear()
textCompare:set_string(config:string_of("access_key"))
local sameText2 = textCompare:contents_equal("", true)
if (config:json_type_of("access_key") ~= 1) or (sameText2) then
print("Supply the base64 account access key.")
return
end
local endpoint = chilkat.StringBuilder.new()
success = endpoint:append(config:string_of("account"))
if not success then
print("Could not prepare the request.")
return
end
success = endpoint:append(".blob.core.windows.net")
if not success then
print("Could not prepare the request.")
return
end
-- resourcePath is already URL-encoded. Encode each path segment once when adapting it.
-- Keep slash separators; names and paths are case-sensitive.
local resourcePath = "/examplecontainer/example.bin"
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
local azAuth = chilkat.AuthAzureStorage.new()
azAuth.account = config:string_of("account")
azAuth.access_key = config:string_of("access_key")
azAuth.service = "Blob"
azAuth.scheme = "SharedKey"
azAuth.xms_version = "2026-04-06"
success = rest:set_auth_azure_storage(azAuth)
if not success then
print("Could not configure Shared Key signing.")
return
end
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
-- Do not replay a write automatically after losing its response.
success = rest:use_connection(connection, false)
if not success then
print("Could not prepare the request.")
return
end
local result = chilkat.Xml.new()
result.strict = true
local partFile = "qa_output/resume.bin.part"
local finalFile = "qa_output/resume.bin"
local checkpointFile = "qa_data/azure/download-checkpoint.json"
local files = chilkat.FileAccess.new()
if files:file_exists(finalFile) then
print("Choose a new final filename; existing output is preserved.")
return
end
local responseText = rest:full_request_no_body("HEAD", resourcePath)
if not rest.last_method_success then
print("Request did not complete; outcome may be uncertain.")
return
end
if rest.response_status_code ~= 200 then
print("HTTP status: " .. rest.response_status_code)
print("Azure error code: " .. rest:response_hdr_by_name("x-ms-error-code"))
print("Request ID: " .. rest:response_hdr_by_name("x-ms-request-id"))
-- Inspect any error body privately; do not log credentials, SAS URLs or payloads.
return
end
local etag = rest:response_hdr_by_name("ETag")
textCompare:clear()
textCompare:set_string(etag)
local sameText3 = textCompare:contents_equal("", true)
if sameText3 then
print("Missing blob ETag.")
return
end
local totalText = rest:response_hdr_by_name("Content-Length")
local totalValue = chilkat.StringBuilder.new()
success = totalValue:append(totalText)
if not success then
print("Could not prepare the request.")
return
end
if (totalValue.length < 1) or (totalValue.length > 10) then
print("Invalid or oversized length for this bounded example.")
return
end
local totalDigits = chilkat.StringBuilder.new()
success = totalDigits:append(totalText)
if not success then
print("Could not prepare the request.")
return
end
local totalRemoved = totalDigits:replace("0", "")
totalRemoved = totalDigits:replace("1", "")
totalRemoved = totalDigits:replace("2", "")
totalRemoved = totalDigits:replace("3", "")
totalRemoved = totalDigits:replace("4", "")
totalRemoved = totalDigits:replace("5", "")
totalRemoved = totalDigits:replace("6", "")
totalRemoved = totalDigits:replace("7", "")
totalRemoved = totalDigits:replace("8", "")
totalRemoved = totalDigits:replace("9", "")
if totalDigits.length ~= 0 then
print("Length must be a decimal string.")
return
end
if (totalValue.length == 10) and ((not totalValue:starts_with("1", true)) and (not totalValue:contents_equal("2000000000", true))) then
print("Length exceeds the 2,000,000,000-byte demonstration bound.")
return
end
local totalNumber = chilkat.JsonObject.new()
success = totalNumber:update_number("value", totalText)
if not success then
print("Could not prepare the request.")
return
end
local total = totalNumber:int_of("value")
local checkpoint = chilkat.JsonObject.new()
checkpoint.strict = true
if files:file_exists(checkpointFile) then
success = checkpoint:load_file(checkpointFile)
if not success then
print("Invalid checkpoint.")
return
end
textCompare:clear()
textCompare:set_string(checkpoint:string_of("path"))
local sameText4 = textCompare:contents_equal(resourcePath, true)
textCompare:clear()
textCompare:set_string(checkpoint:string_of("etag"))
local sameText5 = textCompare:contents_equal(etag, true)
textCompare:clear()
textCompare:set_string(checkpoint:string_of("size"))
local sameText6 = textCompare:contents_equal(totalText, true)
if (checkpoint:string_of("account") ~= config:string_of("account")) or ((not sameText4) or ((not sameText5) or (not sameText6))) then
print("The remote blob or checkpoint target changed. Preserve the old partial output and restart separately.")
return
end
else
if files:file_exists(partFile) then
print("Partial file exists without its checkpoint; refusing to append.")
return
end
success = checkpoint:update_string("account", config:string_of("account"))
if not success then
print("Could not prepare the request.")
return
end
success = checkpoint:update_string("path", resourcePath)
if not success then
print("Could not prepare the request.")
return
end
success = checkpoint:update_string("etag", etag)
if not success then
print("Could not prepare the request.")
return
end
success = checkpoint:update_string("size", totalText)
if not success then
print("Could not prepare the request.")
return
end
success = checkpoint:write_file("qa_data/azure/download-checkpoint.tmp")
if not success then
print("Could not write checkpoint.")
return
end
success = files:file_rename("qa_data/azure/download-checkpoint.tmp", checkpointFile)
if not success then
print("Could not publish checkpoint.")
return
end
end
-- The immutable checkpoint identifies the version. Actual local length is the resume offset.
-- Keep this partial file private, unchanged and exclusive to this one download.
local localSize = "0"
if files:file_exists(partFile) then
localSize = files:file_size_str(partFile)
if not files.last_method_success then
print("Could not get partial-file size.")
return
end
end
local offsetText = localSize
local offsetValue = chilkat.StringBuilder.new()
success = offsetValue:append(offsetText)
if not success then
print("Could not prepare the request.")
return
end
if (offsetValue.length < 1) or (offsetValue.length > 10) then
print("Invalid or oversized length for this bounded example.")
return
end
local offsetDigits = chilkat.StringBuilder.new()
success = offsetDigits:append(offsetText)
if not success then
print("Could not prepare the request.")
return
end
local offsetRemoved = offsetDigits:replace("0", "")
offsetRemoved = offsetDigits:replace("1", "")
offsetRemoved = offsetDigits:replace("2", "")
offsetRemoved = offsetDigits:replace("3", "")
offsetRemoved = offsetDigits:replace("4", "")
offsetRemoved = offsetDigits:replace("5", "")
offsetRemoved = offsetDigits:replace("6", "")
offsetRemoved = offsetDigits:replace("7", "")
offsetRemoved = offsetDigits:replace("8", "")
offsetRemoved = offsetDigits:replace("9", "")
if offsetDigits.length ~= 0 then
print("Length must be a decimal string.")
return
end
if (offsetValue.length == 10) and ((not offsetValue:starts_with("1", true)) and (not offsetValue:contents_equal("2000000000", true))) then
print("Length exceeds the 2,000,000,000-byte demonstration bound.")
return
end
local offsetNumber = chilkat.JsonObject.new()
success = offsetNumber:update_number("value", offsetText)
if not success then
print("Could not prepare the request.")
return
end
local offset = offsetNumber:int_of("value")
if offset > total then
print("Partial file is longer than the selected blob.")
return
end
-- Ensure an empty blob also creates a local file.
success = files:open_for_append(partFile)
if not success then
print("Could not open partial file.")
return
end
files:file_close()
success = rest:add_header("If-Match", etag)
if not success then
print("Could not prepare the request.")
return
end
local chunk = chilkat.BinData.new()
local range = chilkat.StringBuilder.new()
local expectedRange = chilkat.StringBuilder.new()
local expectedLength = chilkat.StringBuilder.new()
while offset < total do
local count = total - offset
if count > 4194304 then
count = 4194304
end
local endByte = offset + count - 1
range:clear()
success = range:append("bytes=")
if not success then
print("Could not prepare the request.")
return
end
success = range:append_int(offset)
if not success then
print("Could not prepare the request.")
return
end
success = range:append("-")
if not success then
print("Could not prepare the request.")
return
end
success = range:append_int(endByte)
if not success then
print("Could not prepare the request.")
return
end
success = rest:add_header("x-ms-range", range:get_as_string())
if not success then
print("Could not prepare the request.")
return
end
expectedRange:clear()
success = expectedRange:append("bytes ")
if not success then
print("Could not prepare the request.")
return
end
success = expectedRange:append_int(offset)
if not success then
print("Could not prepare the request.")
return
end
success = expectedRange:append("-")
if not success then
print("Could not prepare the request.")
return
end
success = expectedRange:append_int(endByte)
if not success then
print("Could not prepare the request.")
return
end
success = expectedRange:append("/")
if not success then
print("Could not prepare the request.")
return
end
success = expectedRange:append(totalText)
if not success then
print("Could not prepare the request.")
return
end
expectedLength:clear()
success = expectedLength:append_int(count)
if not success then
print("Could not prepare the request.")
return
end
rest:disconnect(10)
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
print("TLS reconnection failed.")
return
end
success = rest:use_connection(connection, false)
if not success then
print("Could not prepare the request.")
return
end
success = rest:send_req_no_body("GET", resourcePath)
if not success then
print("Could not prepare the request.")
return
end
local httpStatus = rest:read_response_header()
if httpStatus < 0 then
print("Could not read range response headers.")
return
end
if rest.response_status_code ~= 206 then
print("HTTP status: " .. rest.response_status_code)
print("Azure error code: " .. rest:response_hdr_by_name("x-ms-error-code"))
print("Request ID: " .. rest:response_hdr_by_name("x-ms-request-id"))
-- Inspect any error body privately; do not log credentials, SAS URLs or payloads.
return
end
textCompare:clear()
textCompare:set_string(rest:response_hdr_by_name("ETag"))
local sameText7 = textCompare:contents_equal(etag, true)
if (not sameText7) or ((rest:response_hdr_by_name("Content-Range") ~= expectedRange:get_as_string()) or (rest:response_hdr_by_name("Content-Length") ~= expectedLength:get_as_string())) then
print("Unexpected range response; no bytes appended.")
return
end
success = chunk:clear()
if not success then
print("Could not prepare the request.")
return
end
success = rest:read_resp_bd(chunk)
if not success then
print("Incomplete range body; no bytes appended.")
return
end
if chunk.num_bytes ~= count then
print("Wrong byte count; no bytes appended.")
return
end
success = files:open_for_append(partFile)
if not success then
print("Could not reopen partial file.")
return
end
success = files:file_write_bd(chunk, 0, 0)
files:file_close()
if not success then
print("Local write failed. Inspect the partial file before retrying.")
return
end
offset = offset + count
end
success = files:file_rename(partFile, finalFile)
if not success then
print("Could not publish completed download.")
return
end
print("Download complete. Retain or archive the checkpoint with the completed file.")