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