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

Azure Blob: Resume a Block Upload from a Checkpoint

See more Azure Cloud Storage Examples

Persist the destination, source size/SHA-256, block size and unique upload ID before staging any blocks. On a later run, verify the source, get the uncommitted block list, skip matching blocks, upload missing blocks, and commit in source order. Block IDs are derived from the saved upload ID and fixed-width index, so a restart uses the same IDs.

Use one process per checkpoint and keep its source and destination exclusively controlled. The example does not replace an existing blob. Commit metadata lets a restart recognize its own completed upload after an uncertain response; otherwise an existing destination is an error. Remote block size is checked, but the source fingerprint and unique namespace are what associate the blocks with this upload. Stale uncommitted blocks can expire; missing blocks are uploaded again. Empty files commit an empty block list.

The sample uses 4 MiB blocks and at most 50,000 blocks; source sizes stay strings and block indexes use int. It fingerprints the whole source at start and before commit, trading read time for change detection. Keep checkpoint files private and unchanged. A corrupt checkpoint fails closed; choose a fresh checkpoint and destination deliberately rather than discarding state automatically.

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.

Microsoft 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
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 responseBody = chilkat.StringBuilder.new()
local result = chilkat.Xml.new()
result.strict = true
local sourceFile = "qa_data/bin/sample.bin"
local checkpointFile = "qa_data/azure/upload-checkpoint.json"
local input = chilkat.FileAccess.new()
success = input:open_for_read(sourceFile)
if not success then
    print("Could not open upload source.")
    input:file_close()
    return
end

local sourceSize = input:file_size_str(sourceFile)
if not input.last_method_success then
    print("Could not read source size.")
    input:file_close()
    return
end

local blockSize = 4194304
local numBlocks = input:get_num_blocks(blockSize)
if (not input.last_method_success) or ((numBlocks < 0) or (numBlocks > 50000)) then
    print("Source exceeds the 50,000-block demonstration bound.")
    input:file_close()
    return
end

local hash = chilkat.Crypt2.new()
hash.hash_algorithm = "sha256"
hash.encoding_mode = "hex_lower"
local fingerprint = hash:hash_file_enc(sourceFile)
if not hash.last_method_success then
    print("Could not fingerprint source.")
    input:file_close()
    return
end

local checkpoint = chilkat.JsonObject.new()
checkpoint.strict = true
local files = chilkat.FileAccess.new()
if files:file_exists(checkpointFile) then
    success = checkpoint:load_file(checkpointFile)
    if not success then
        print("Invalid checkpoint; do not silently start another upload.")
        input:file_close()
        return
    end

    textCompare:clear()
    textCompare:set_string(checkpoint:string_of("path"))
    local sameText3 = textCompare:contents_equal(resourcePath, true)
    textCompare:clear()
    textCompare:set_string(checkpoint:string_of("sha256"))
    local sameText4 = textCompare:contents_equal(fingerprint, true)
    textCompare:clear()
    textCompare:set_string(checkpoint:string_of("size"))
    local sameText5 = textCompare:contents_equal(sourceSize, true)
    if (checkpoint:string_of("account") ~= config:string_of("account")) or ((not sameText3) or ((not sameText4) or ((not sameText5) or (checkpoint:int_of("block_size") ~= blockSize)))) then
        print("Checkpoint target or source changed. Choose a new checkpoint/target deliberately.")
        input:file_close()
        return
    end

    textCompare:clear()
    textCompare:set_string(checkpoint:string_of("upload_id"))
    local sameText6 = textCompare:contents_equal("", true)
    if sameText6 then
        print("Missing checkpoint upload ID.")
        input:file_close()
        return
    end
else
    local newId = hash:generate_uuid()
    if not hash.last_method_success then
        print("Could not generate upload ID.")
        input:file_close()
        return
    end

    success = checkpoint:update_string("account", config:string_of("account"))
    if not success then
        print("Could not prepare the request.")
        input:file_close()
        return
    end

    success = checkpoint:update_string("path", resourcePath)
    if not success then
        print("Could not prepare the request.")
        input:file_close()
        return
    end

    success = checkpoint:update_string("sha256", fingerprint)
    if not success then
        print("Could not prepare the request.")
        input:file_close()
        return
    end

    success = checkpoint:update_string("size", sourceSize)
    if not success then
        print("Could not prepare the request.")
        input:file_close()
        return
    end

    success = checkpoint:update_int("block_size", blockSize)
    if not success then
        print("Could not prepare the request.")
        input:file_close()
        return
    end

    success = checkpoint:update_string("upload_id", newId)
    if not success then
        print("Could not prepare the request.")
        input:file_close()
        return
    end

    success = checkpoint:write_file("qa_data/azure/upload-checkpoint.tmp")
    if not success then
        print("Could not write checkpoint.")
        input:file_close()
        return
    end

    success = files:file_rename("qa_data/azure/upload-checkpoint.tmp", checkpointFile)
    if not success then
        print("Could not publish checkpoint.")
        input:file_close()
        return
    end
end

local uploadId = checkpoint:string_of("upload_id")
local idCheck = chilkat.StringBuilder.new()
success = idCheck:append(uploadId)
if not success then
    print("Could not prepare the request.")
    input:file_close()
    return
end

if idCheck.length ~= 36 then
    print("Invalid upload ID length in checkpoint.")
    input:file_close()
    return
end

-- Reconcile an uncertain commit before staging anything else.
local responseText = rest:full_request_no_body("HEAD", resourcePath)
if not rest.last_method_success then
    print("Could not inspect destination.")
    input:file_close()
    return
end

if rest.response_status_code == 200 then
    textCompare:clear()
    textCompare:set_string(rest:response_hdr_by_name("x-ms-meta-upload-id"))
    local sameText7 = textCompare:contents_equal(uploadId, true)
    textCompare:clear()
    textCompare:set_string(rest:response_hdr_by_name("x-ms-meta-source-sha256"))
    local sameText8 = textCompare:contents_equal(fingerprint, true)
    textCompare:clear()
    textCompare:set_string(rest:response_hdr_by_name("Content-Length"))
    local sameText9 = textCompare:contents_equal(sourceSize, true)
    if (not sameText7) or ((not sameText8) or (not sameText9)) then
        print("Destination exists and is not this completed upload. Refusing to replace it.")
        input:file_close()
        return
    end

    print("Upload already committed. Keep the checkpoint until the application records completion.")
    input:file_close()
    return
end

textCompare:clear()
textCompare:set_string(rest:response_hdr_by_name("x-ms-error-code"))
local sameText10 = textCompare:contents_equal("BlobNotFound", true)
if (rest.response_status_code ~= 404) or (not sameText10) then
    print("Expected an absent blob in an existing container.")
    input:file_close()
    return
end

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

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

rest:disconnect(10)
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
    print("TLS reconnection failed.")
    input:file_close()
    return
end

success = rest:use_connection(connection, false)
if not success then
    print("Could not prepare the request.")
    input:file_close()
    return
end

responseText = rest:full_request_no_body("GET", resourcePath)
if not rest.last_method_success then
    print("Could not reconcile uploaded blocks.")
    input:file_close()
    return
end

local remoteBlocks = chilkat.Hashtable.new()
if rest.response_status_code == 200 then
    success = result:load_xml(responseText)
    if not success then
        print("Expected well-formed XML.")
        input:file_close()
        return
    end

    if not result:tag_equals("BlockList") then
        print("Unexpected XML response root.")
        input:file_close()
        return
    end

    local remoteCount = result:num_children_at("UncommittedBlocks")
    local j = 0
    while j < remoteCount do
        result.i = j
        local remoteId = result:get_child_content("UncommittedBlocks|Block[i]|Name")
        local remoteSize = result:get_child_content("UncommittedBlocks|Block[i]|Size")
        textCompare:clear()
        textCompare:set_string(remoteId)
        local sameText11 = textCompare:contents_equal("", true)
        textCompare:clear()
        textCompare:set_string(remoteSize)
        local sameText12 = textCompare:contents_equal("", true)
        if (sameText11) or (sameText12) then
            print("Malformed remote block listing.")
            input:file_close()
            return
        end

        success = remoteBlocks:add_str(remoteId, remoteSize)
        if not success then
            print("Could not prepare the request.")
            input:file_close()
            return
        end

        j = j + 1
    end
else
    textCompare:clear()
    textCompare:set_string(rest:response_hdr_by_name("x-ms-error-code"))
    local sameText13 = textCompare:contents_equal("BlobNotFound", true)
    if (rest.response_status_code ~= 404) or (not sameText13) then
        print("Block listing failed.")
        input:file_close()
        return
    end
end

local blocks = chilkat.Xml.new()
blocks.tag = "BlockList"
local chunk = chilkat.BinData.new()
local blockText = chilkat.StringBuilder.new()
local sizeText = chilkat.StringBuilder.new()
local i = 0
while i < numBlocks do
    success = chunk:clear()
    if not success then
        print("Could not prepare the request.")
        input:file_close()
        return
    end

    success = input:read_block_bd(i, blockSize, chunk)
    if not success then
        print("Could not read source block.")
        input:file_close()
        return
    end

    if (chunk.num_bytes < 1) or ((i < numBlocks - 1) and (chunk.num_bytes ~= blockSize)) then
        print("Source changed or an incomplete read occurred.")
        input:file_close()
        return
    end

    blockText:clear()
    success = blockText:append(uploadId)
    if not success then
        print("Could not prepare the request.")
        input:file_close()
        return
    end

    success = blockText:append(input:gen_block_id(i, 5, "ascii"))
    if not success then
        print("Could not prepare the request.")
        input:file_close()
        return
    end

    success = blockText:encode("base64", "utf-8")
    if not success then
        print("Could not prepare the request.")
        input:file_close()
        return
    end

    local blockId = blockText:get_as_string()
    sizeText:clear()
    success = sizeText:append_int(chunk.num_bytes)
    if not success then
        print("Could not prepare the request.")
        input:file_close()
        return
    end

    local uploadBlock = true
    if remoteBlocks:contains(blockId) then
        if remoteBlocks:lookup_str(blockId) ~= sizeText:get_as_string() then
            print("Remote block size differs; do not commit this upload.")
            input:file_close()
            return
        end

        uploadBlock = false
    end

    if uploadBlock then
        success = rest:clear_all_query_params()
        if not success then
            print("Could not prepare the request.")
            input:file_close()
            return
        end

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

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

        rest:disconnect(10)
        success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
        if not success then
            print("TLS reconnection failed.")
            input:file_close()
            return
        end

        success = rest:use_connection(connection, false)
        if not success then
            print("Could not prepare the request.")
            input:file_close()
            return
        end

        responseBody:clear()
        success = rest:full_request_bd("PUT", resourcePath, chunk, responseBody)
        if not success then
            print("Request did not complete; outcome may be uncertain.")
            input:file_close()
            return
        end

        if rest.response_status_code ~= 201 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.
            input:file_close()
            return
        end
    end

    blocks:new_child2("Uncommitted", blockId)
    i = i + 1
end

-- Rehash before commit. Do not modify the source or run concurrent writers.
local finalFingerprint = hash:hash_file_enc(sourceFile)
textCompare:clear()
textCompare:set_string(finalFingerprint)
local sameText14 = textCompare:contents_equal(fingerprint, true)
if (not hash.last_method_success) or (not sameText14) then
    print("Source changed during staging; commit cancelled.")
    input:file_close()
    return
end

input:file_close()
success = rest:clear_all_query_params()
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_query_param("comp", "blocklist")
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

success = rest:add_header("x-ms-blob-content-type", "application/octet-stream")
if not success then
    print("Could not prepare the request.")
    return
end

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

success = rest:add_header("x-ms-meta-upload-id", uploadId)
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("x-ms-meta-source-sha256", fingerprint)
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

responseText = rest:full_request_string("PUT", resourcePath, blocks:get_xml())
if not rest.last_method_success then
    print("Request did not complete; outcome may be uncertain.")
    return
end

if rest.response_status_code ~= 201 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

print("Upload committed. Retain the checkpoint for reconciliation until completion is recorded.")