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 B4X Downloads
Dim success As Boolean = False
' StringBuilder compares text by value in every generated language.
Dim textCompare As ChilkatStringBuilder
textCompare.Initialize
' Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False
Dim config As ChilkatJsonObject
config.Initialize
config.Strict = True
success = config.LoadFile("qa_data/azure/storage.json")
If success <> True Then
Log("Could not load private Azure configuration.")
Return
End If
textCompare.Clear
textCompare.SetString(config.StringOf("account"))
Dim sameText1 As Boolean = textCompare.ContentsEqual("", True)
If (config.JsonTypeOf("account") <> 1) Or (sameText1 = True) Then
Log("Supply the storage account name.")
Return
End If
' access_key is the base64 account key, not a connection string or SAS.
textCompare.Clear
textCompare.SetString(config.StringOf("access_key"))
Dim sameText2 As Boolean = textCompare.ContentsEqual("", True)
If (config.JsonTypeOf("access_key") <> 1) Or (sameText2 = True) Then
Log("Supply the base64 account access key.")
Return
End If
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
success = endpoint.Append(config.StringOf("account"))
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = endpoint.Append(".blob.core.windows.net")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
' resourcePath is already URL-encoded. Encode each path segment once when adapting it.
' Keep slash separators; names and paths are case-sensitive.
Dim resourcePath As String = "/examplecontainer/example.bin"
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
Dim azAuth As ChilkatAuthAzureStorage
azAuth.Initialize
azAuth.Account = config.StringOf("account")
azAuth.AccessKey = config.StringOf("access_key")
azAuth.Service = "Blob"
azAuth.Scheme = "SharedKey"
azAuth.XMsVersion = "2026-04-06"
success = rest.SetAuthAzureStorage(azAuth)
If success <> True Then
Log("Could not configure Shared Key signing.")
Return
End If
Dim connection As ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
Log("TLS connection failed; inspect diagnostics privately.")
Return
End If
' Do not replay a write automatically after losing its response.
success = rest.UseConnection(connection, False)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim responseText As String
Dim result As ChilkatXml
result.Initialize
result.Strict = True
Dim partFile As String = "qa_output/resume.bin.part"
Dim finalFile As String = "qa_output/resume.bin"
Dim checkpointFile As String = "qa_data/azure/download-checkpoint.json"
Dim files As ChilkatFileAccess
files.Initialize
If files.FileExists(finalFile) = True Then
Log("Choose a new final filename; existing output is preserved.")
Return
End If
responseText = rest.FullRequestNoBody("HEAD", resourcePath)
If rest.LastMethodSuccess <> True Then
Log("Request did not complete; outcome may be uncertain.")
Return
End If
If rest.ResponseStatusCode <> 200 Then
Log("HTTP status: " & rest.ResponseStatusCode)
Log("Azure error code: " & rest.ResponseHdrByName("x-ms-error-code"))
Log("Request ID: " & rest.ResponseHdrByName("x-ms-request-id"))
' Inspect any error body privately; do not log credentials, SAS URLs or payloads.
Return
End If
Dim etag As String = rest.ResponseHdrByName("ETag")
textCompare.Clear
textCompare.SetString(etag)
Dim sameText3 As Boolean = textCompare.ContentsEqual("", True)
If sameText3 = True Then
Log("Missing blob ETag.")
Return
End If
Dim totalText As String = rest.ResponseHdrByName("Content-Length")
Dim totalValue As ChilkatStringBuilder
totalValue.Initialize
success = totalValue.Append(totalText)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
If (totalValue.Length < 1) Or (totalValue.Length > 10) Then
Log("Invalid or oversized length for this bounded example.")
Return
End If
Dim totalDigits As ChilkatStringBuilder
totalDigits.Initialize
success = totalDigits.Append(totalText)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim totalRemoved As Int = 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.Length <> 0 Then
Log("Length must be a decimal string.")
Return
End If
If (totalValue.Length = 10) And (totalValue.StartsWith("1", True) <> True) And (totalValue.ContentsEqual("2000000000", True) <> True) Then
Log("Length exceeds the 2,000,000,000-byte demonstration bound.")
Return
End If
Dim totalNumber As ChilkatJsonObject
totalNumber.Initialize
success = totalNumber.UpdateNumber("value", totalText)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim total As Int = totalNumber.IntOf("value")
Dim checkpoint As ChilkatJsonObject
checkpoint.Initialize
checkpoint.Strict = True
If files.FileExists(checkpointFile) = True Then
success = checkpoint.LoadFile(checkpointFile)
If success <> True Then
Log("Invalid checkpoint.")
Return
End If
textCompare.Clear
textCompare.SetString(checkpoint.StringOf("path"))
Dim sameText4 As Boolean = textCompare.ContentsEqual(resourcePath, True)
textCompare.Clear
textCompare.SetString(checkpoint.StringOf("etag"))
Dim sameText5 As Boolean = textCompare.ContentsEqual(etag, True)
textCompare.Clear
textCompare.SetString(checkpoint.StringOf("size"))
Dim sameText6 As Boolean = textCompare.ContentsEqual(totalText, True)
If (checkpoint.StringOf("account") <> config.StringOf("account")) Or (sameText4 <> True) Or (sameText5 <> True) Or (sameText6 <> True) Then
Log("The remote blob or checkpoint target changed. Preserve the old partial output and restart separately.")
Return
End If
Else
If files.FileExists(partFile) = True Then
Log("Partial file exists without its checkpoint; refusing to append.")
Return
End If
success = checkpoint.UpdateString("account", config.StringOf("account"))
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = checkpoint.UpdateString("path", resourcePath)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = checkpoint.UpdateString("etag", etag)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = checkpoint.UpdateString("size", totalText)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = checkpoint.WriteFile("qa_data/azure/download-checkpoint.tmp")
If success <> True Then
Log("Could not write checkpoint.")
Return
End If
success = files.FileRename("qa_data/azure/download-checkpoint.tmp", checkpointFile)
If success <> True Then
Log("Could not publish checkpoint.")
Return
End If
End If
' 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.
Dim localSize As String = "0"
If files.FileExists(partFile) = True Then
localSize = files.FileSizeStr(partFile)
If files.LastMethodSuccess <> True Then
Log("Could not get partial-file size.")
Return
End If
End If
Dim offsetText As String = localSize
Dim offsetValue As ChilkatStringBuilder
offsetValue.Initialize
success = offsetValue.Append(offsetText)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
If (offsetValue.Length < 1) Or (offsetValue.Length > 10) Then
Log("Invalid or oversized length for this bounded example.")
Return
End If
Dim offsetDigits As ChilkatStringBuilder
offsetDigits.Initialize
success = offsetDigits.Append(offsetText)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim offsetRemoved As Int = 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.Length <> 0 Then
Log("Length must be a decimal string.")
Return
End If
If (offsetValue.Length = 10) And (offsetValue.StartsWith("1", True) <> True) And (offsetValue.ContentsEqual("2000000000", True) <> True) Then
Log("Length exceeds the 2,000,000,000-byte demonstration bound.")
Return
End If
Dim offsetNumber As ChilkatJsonObject
offsetNumber.Initialize
success = offsetNumber.UpdateNumber("value", offsetText)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim offset As Int = offsetNumber.IntOf("value")
If offset > total Then
Log("Partial file is longer than the selected blob.")
Return
End If
' Ensure an empty blob also creates a local file.
success = files.OpenForAppend(partFile)
If success <> True Then
Log("Could not open partial file.")
Return
End If
files.FileClose
success = rest.AddHeader("If-Match", etag)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim chunk As ChilkatBinData
chunk.Initialize
Dim range As ChilkatStringBuilder
range.Initialize
Dim expectedRange As ChilkatStringBuilder
expectedRange.Initialize
Dim expectedLength As ChilkatStringBuilder
expectedLength.Initialize
Do While (offset < total)
Dim count As Int = total - offset
If count > 4194304 Then
count = 4194304
End If
Dim endByte As Int = offset + count - 1
range.Clear
success = range.Append("bytes=")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = range.AppendInt(offset)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = range.Append("-")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = range.AppendInt(endByte)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = rest.AddHeader("x-ms-range", range.GetAsString)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
expectedRange.Clear
success = expectedRange.Append("bytes ")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = expectedRange.AppendInt(offset)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = expectedRange.Append("-")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = expectedRange.AppendInt(endByte)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = expectedRange.Append("/")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = expectedRange.Append(totalText)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
expectedLength.Clear
success = expectedLength.AppendInt(count)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
rest.Disconnect(10)
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
Log("TLS reconnection failed.")
Return
End If
success = rest.UseConnection(connection, False)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = rest.SendReqNoBody("GET", resourcePath)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim httpStatus As Int = rest.ReadResponseHeader
If httpStatus < 0 Then
Log("Could not read range response headers.")
Return
End If
If rest.ResponseStatusCode <> 206 Then
Log("HTTP status: " & rest.ResponseStatusCode)
Log("Azure error code: " & rest.ResponseHdrByName("x-ms-error-code"))
Log("Request ID: " & rest.ResponseHdrByName("x-ms-request-id"))
' Inspect any error body privately; do not log credentials, SAS URLs or payloads.
Return
End If
textCompare.Clear
textCompare.SetString(rest.ResponseHdrByName("ETag"))
Dim sameText7 As Boolean = textCompare.ContentsEqual(etag, True)
If (sameText7 <> True) Or (rest.ResponseHdrByName("Content-Range") <> expectedRange.GetAsString) Or (rest.ResponseHdrByName("Content-Length") <> expectedLength.GetAsString) Then
Log("Unexpected range response; no bytes appended.")
Return
End If
success = chunk.Clear
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = rest.ReadRespBd(chunk)
If success <> True Then
Log("Incomplete range body; no bytes appended.")
Return
End If
If chunk.NumBytes <> count Then
Log("Wrong byte count; no bytes appended.")
Return
End If
success = files.OpenForAppend(partFile)
If success <> True Then
Log("Could not reopen partial file.")
Return
End If
success = files.FileWriteBd(chunk, 0, 0)
files.FileClose
If success <> True Then
Log("Local write failed. Inspect the partial file before retrying.")
Return
End If
offset = offset + count
Loop
success = files.FileRename(partFile, finalFile)
If success <> True Then
Log("Could not publish completed download.")
Return
End If
Log("Download complete. Retain or archive the checkpoint with the completed file.")