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

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.

Microsoft reference.

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

#  StringBuilder compares text by value in every generated language.
textCompare = Chilkat::CkStringBuilder.new()
#  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false
config = Chilkat::CkJsonObject.new()
config.put_Strict(true)
success = config.LoadFile("qa_data/azure/storage.json")
if (success != true)
    print "Could not load private Azure configuration." + "\n";
    exit
end

textCompare.Clear()
textCompare.SetString(config.stringOf("account"))
sameText1 = textCompare.ContentsEqual("",true)
if ((config.JsonTypeOf("account") != 1) or (sameText1 == true))
    print "Supply the storage account name." + "\n";
    exit
end

#  access_key is the base64 account key, not a connection string or SAS.
textCompare.Clear()
textCompare.SetString(config.stringOf("access_key"))
sameText2 = textCompare.ContentsEqual("",true)
if ((config.JsonTypeOf("access_key") != 1) or (sameText2 == true))
    print "Supply the base64 account access key." + "\n";
    exit
end

endpoint = Chilkat::CkStringBuilder.new()
success = endpoint.Append(config.stringOf("account"))
if (success != true)
    print "Could not prepare the request." + "\n";
    exit
end

success = endpoint.Append(".blob.core.windows.net")
if (success != true)
    print "Could not prepare the request." + "\n";
    exit
end

#  resourcePath is already URL-encoded. Encode each path segment once when adapting it.
#  Keep slash separators; names and paths are case-sensitive.
resourcePath = "/examplecontainer/example.bin"
rest = Chilkat::CkRest.new()
rest.put_ConnectTimeoutMs(20000)
rest.put_IdleTimeoutMs(60000)
azAuth = Chilkat::CkAuthAzureStorage.new()
azAuth.put_Account(config.stringOf("account"))
azAuth.put_AccessKey(config.stringOf("access_key"))
azAuth.put_Service("Blob")
azAuth.put_Scheme("SharedKey")
azAuth.put_XMsVersion("2026-04-06")
success = rest.SetAuthAzureStorage(azAuth)
if (success != true)
    print "Could not configure Shared Key signing." + "\n";
    exit
end

connection = Chilkat::CkSocket.new()
connection.put_RequireSslCertVerify(true)
connection.put_MaxReadIdleMs(60000)
connection.put_MaxSendIdleMs(60000)
success = connection.Connect(endpoint.getAsString(),443,true,20000)
if (success != true)
    print "TLS connection failed; inspect diagnostics privately." + "\n";
    exit
end

#  Do not replay a write automatically after losing its response.
success = rest.UseConnection(connection,false)
if (success != true)
    print "Could not prepare the request." + "\n";
    exit
end

result = Chilkat::CkXml.new()
result.put_Strict(true)
partFile = "qa_output/resume.bin.part"
finalFile = "qa_output/resume.bin"
checkpointFile = "qa_data/azure/download-checkpoint.json"
files = Chilkat::CkFileAccess.new()
if (files.FileExists(finalFile) == true)
    print "Choose a new final filename; existing output is preserved." + "\n";
    exit
end

responseText = rest.fullRequestNoBody("HEAD",resourcePath)
if (rest.get_LastMethodSuccess() != true)
    print "Request did not complete; outcome may be uncertain." + "\n";
    exit
end

if (rest.get_ResponseStatusCode() != 200)
    print "HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
    print "Azure error code: " + rest.responseHdrByName("x-ms-error-code") + "\n";
    print "Request ID: " + rest.responseHdrByName("x-ms-request-id") + "\n";
    #  Inspect any error body privately; do not log credentials, SAS URLs or payloads.
    exit
end

etag = rest.responseHdrByName("ETag")
textCompare.Clear()
textCompare.SetString(etag)
sameText3 = textCompare.ContentsEqual("",true)
if (sameText3 == true)
    print "Missing blob ETag." + "\n";
    exit
end

totalText = rest.responseHdrByName("Content-Length")
totalValue = Chilkat::CkStringBuilder.new()
success = totalValue.Append(totalText)
if (success != true)
    print "Could not prepare the request." + "\n";
    exit
end

if ((totalValue.get_Length() < 1) or (totalValue.get_Length() > 10))
    print "Invalid or oversized length for this bounded example." + "\n";
    exit
end

totalDigits = Chilkat::CkStringBuilder.new()
success = totalDigits.Append(totalText)
if (success != true)
    print "Could not prepare the request." + "\n";
    exit
end

totalRemoved = 0
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.get_Length() != 0)
    print "Length must be a decimal string." + "\n";
    exit
end

if ((totalValue.get_Length() == 10) and (totalValue.StartsWith("1",true) != true) and (totalValue.ContentsEqual("2000000000",true) != true))
    print "Length exceeds the 2,000,000,000-byte demonstration bound." + "\n";
    exit
end

totalNumber = Chilkat::CkJsonObject.new()
success = totalNumber.UpdateNumber("value",totalText)
if (success != true)
    print "Could not prepare the request." + "\n";
    exit
end

total = totalNumber.IntOf("value")
checkpoint = Chilkat::CkJsonObject.new()
checkpoint.put_Strict(true)
if (files.FileExists(checkpointFile) == true)
    success = checkpoint.LoadFile(checkpointFile)
    if (success != true)
        print "Invalid checkpoint." + "\n";
        exit
    end

    textCompare.Clear()
    textCompare.SetString(checkpoint.stringOf("path"))
    sameText4 = textCompare.ContentsEqual(resourcePath,true)
    textCompare.Clear()
    textCompare.SetString(checkpoint.stringOf("etag"))
    sameText5 = textCompare.ContentsEqual(etag,true)
    textCompare.Clear()
    textCompare.SetString(checkpoint.stringOf("size"))
    sameText6 = textCompare.ContentsEqual(totalText,true)
    if ((checkpoint.stringOf("account") != config.stringOf("account")) or (sameText4 != true) or (sameText5 != true) or (sameText6 != true))
        print "The remote blob or checkpoint target changed. Preserve the old partial output and restart separately." + "\n";
        exit
    end

else
    if (files.FileExists(partFile) == true)
        print "Partial file exists without its checkpoint; refusing to append." + "\n";
        exit
    end

    success = checkpoint.UpdateString("account",config.stringOf("account"))
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = checkpoint.UpdateString("path",resourcePath)
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = checkpoint.UpdateString("etag",etag)
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = checkpoint.UpdateString("size",totalText)
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = checkpoint.WriteFile("qa_data/azure/download-checkpoint.tmp")
    if (success != true)
        print "Could not write checkpoint." + "\n";
        exit
    end

    success = files.FileRename("qa_data/azure/download-checkpoint.tmp",checkpointFile)
    if (success != true)
        print "Could not publish checkpoint." + "\n";
        exit
    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.
localSize = "0"
if (files.FileExists(partFile) == true)
    localSize = files.fileSizeStr(partFile)
    if (files.get_LastMethodSuccess() != true)
        print "Could not get partial-file size." + "\n";
        exit
    end

end

offsetText = localSize
offsetValue = Chilkat::CkStringBuilder.new()
success = offsetValue.Append(offsetText)
if (success != true)
    print "Could not prepare the request." + "\n";
    exit
end

if ((offsetValue.get_Length() < 1) or (offsetValue.get_Length() > 10))
    print "Invalid or oversized length for this bounded example." + "\n";
    exit
end

offsetDigits = Chilkat::CkStringBuilder.new()
success = offsetDigits.Append(offsetText)
if (success != true)
    print "Could not prepare the request." + "\n";
    exit
end

offsetRemoved = 0
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.get_Length() != 0)
    print "Length must be a decimal string." + "\n";
    exit
end

if ((offsetValue.get_Length() == 10) and (offsetValue.StartsWith("1",true) != true) and (offsetValue.ContentsEqual("2000000000",true) != true))
    print "Length exceeds the 2,000,000,000-byte demonstration bound." + "\n";
    exit
end

offsetNumber = Chilkat::CkJsonObject.new()
success = offsetNumber.UpdateNumber("value",offsetText)
if (success != true)
    print "Could not prepare the request." + "\n";
    exit
end

offset = offsetNumber.IntOf("value")
if (offset > total)
    print "Partial file is longer than the selected blob." + "\n";
    exit
end

#  Ensure an empty blob also creates a local file.
success = files.OpenForAppend(partFile)
if (success != true)
    print "Could not open partial file." + "\n";
    exit
end

files.FileClose()
success = rest.AddHeader("If-Match",etag)
if (success != true)
    print "Could not prepare the request." + "\n";
    exit
end

chunk = Chilkat::CkBinData.new()
range = Chilkat::CkStringBuilder.new()
expectedRange = Chilkat::CkStringBuilder.new()
expectedLength = Chilkat::CkStringBuilder.new()
while (offset < total)
    count = total - offset
    if (count > 4194304)
        count = 4194304
    end

    endByte = offset + count - 1
    range.Clear()
    success = range.Append("bytes=")
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = range.AppendInt(offset)
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = range.Append("-")
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = range.AppendInt(endByte)
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = rest.AddHeader("x-ms-range",range.getAsString())
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    expectedRange.Clear()
    success = expectedRange.Append("bytes ")
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = expectedRange.AppendInt(offset)
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = expectedRange.Append("-")
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = expectedRange.AppendInt(endByte)
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = expectedRange.Append("/")
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = expectedRange.Append(totalText)
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    expectedLength.Clear()
    success = expectedLength.AppendInt(count)
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    rest.Disconnect(10)
    success = connection.Connect(endpoint.getAsString(),443,true,20000)
    if (success != true)
        print "TLS reconnection failed." + "\n";
        exit
    end

    success = rest.UseConnection(connection,false)
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = rest.SendReqNoBody("GET",resourcePath)
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    httpStatus = rest.ReadResponseHeader()
    if (httpStatus < 0)
        print "Could not read range response headers." + "\n";
        exit
    end

    if (rest.get_ResponseStatusCode() != 206)
        print "HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
        print "Azure error code: " + rest.responseHdrByName("x-ms-error-code") + "\n";
        print "Request ID: " + rest.responseHdrByName("x-ms-request-id") + "\n";
        #  Inspect any error body privately; do not log credentials, SAS URLs or payloads.
        exit
    end

    textCompare.Clear()
    textCompare.SetString(rest.responseHdrByName("ETag"))
    sameText7 = textCompare.ContentsEqual(etag,true)
    if ((sameText7 != true) or (rest.responseHdrByName("Content-Range") != expectedRange.getAsString()) or (rest.responseHdrByName("Content-Length") != expectedLength.getAsString()))
        print "Unexpected range response; no bytes appended." + "\n";
        exit
    end

    success = chunk.Clear()
    if (success != true)
        print "Could not prepare the request." + "\n";
        exit
    end

    success = rest.ReadRespBd(chunk)
    if (success != true)
        print "Incomplete range body; no bytes appended." + "\n";
        exit
    end

    if (chunk.get_NumBytes() != count)
        print "Wrong byte count; no bytes appended." + "\n";
        exit
    end

    success = files.OpenForAppend(partFile)
    if (success != true)
        print "Could not reopen partial file." + "\n";
        exit
    end

    success = files.FileWriteBd(chunk,0,0)
    files.FileClose()
    if (success != true)
        print "Local write failed. Inspect the partial file before retrying." + "\n";
        exit
    end

    offset = offset + count
end
success = files.FileRename(partFile,finalFile)
if (success != true)
    print "Could not publish completed download." + "\n";
    exit
end

print "Download complete. Retain or archive the checkpoint with the completed file." + "\n";