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 Delphi ActiveX Downloads
var
success: Integer;
textCompare: TChilkatStringBuilder;
config: TChilkatJsonObject;
sameText1: Integer;
sameText2: Integer;
endpoint: TChilkatStringBuilder;
resourcePath: WideString;
rest: TChilkatRest;
azAuth: TChilkatAuthAzureStorage;
connection: TChilkatSocket;
responseText: WideString;
result: TChilkatXml;
partFile: WideString;
finalFile: WideString;
checkpointFile: WideString;
files: TCkFileAccess;
etag: WideString;
sameText3: Integer;
totalText: WideString;
totalValue: TChilkatStringBuilder;
totalDigits: TChilkatStringBuilder;
totalRemoved: Integer;
totalNumber: TChilkatJsonObject;
total: Integer;
checkpoint: TChilkatJsonObject;
sameText4: Integer;
sameText5: Integer;
sameText6: Integer;
localSize: WideString;
offsetText: WideString;
offsetValue: TChilkatStringBuilder;
offsetDigits: TChilkatStringBuilder;
offsetRemoved: Integer;
offsetNumber: TChilkatJsonObject;
offset: Integer;
chunk: TChilkatBinData;
range: TChilkatStringBuilder;
expectedRange: TChilkatStringBuilder;
expectedLength: TChilkatStringBuilder;
count: Integer;
endByte: Integer;
httpStatus: Integer;
sameText7: Integer;
begin
success := 0;
// StringBuilder compares text by value in every generated language.
textCompare := TChilkatStringBuilder.Create(Self);
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success := 0;
config := TChilkatJsonObject.Create(Self);
config.Strict := 1;
success := config.LoadFile('qa_data/azure/storage.json');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not load private Azure configuration.');
Exit;
end;
textCompare.Clear();
textCompare.SetString(config.StringOf('account'));
sameText1 := textCompare.ContentsEqual('',1);
if ((config.JsonTypeOf('account') <> 1) or (sameText1 = 1)) then
begin
Memo1.Lines.Add('Supply the storage account name.');
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('',1);
if ((config.JsonTypeOf('access_key') <> 1) or (sameText2 = 1)) then
begin
Memo1.Lines.Add('Supply the base64 account access key.');
Exit;
end;
endpoint := TChilkatStringBuilder.Create(Self);
success := endpoint.Append(config.StringOf('account'));
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := endpoint.Append('.blob.core.windows.net');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
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 := TChilkatRest.Create(Self);
rest.ConnectTimeoutMs := 20000;
rest.IdleTimeoutMs := 60000;
azAuth := TChilkatAuthAzureStorage.Create(Self);
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.ControlInterface);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not configure Shared Key signing.');
Exit;
end;
connection := TChilkatSocket.Create(Self);
connection.RequireSslCertVerify := 1;
connection.MaxReadIdleMs := 60000;
connection.MaxSendIdleMs := 60000;
success := connection.Connect(endpoint.GetAsString(),443,1,20000);
if (success <> 1) then
begin
Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
Exit;
end;
// Do not replay a write automatically after losing its response.
success := rest.UseConnection(connection.ControlInterface,0);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
result := TChilkatXml.Create(Self);
result.Strict := 1;
partFile := 'qa_output/resume.bin.part';
finalFile := 'qa_output/resume.bin';
checkpointFile := 'qa_data/azure/download-checkpoint.json';
files := TCkFileAccess.Create(Self);
if (files.FileExists(finalFile) = 1) then
begin
Memo1.Lines.Add('Choose a new final filename; existing output is preserved.');
Exit;
end;
responseText := rest.FullRequestNoBody('HEAD',resourcePath);
if (rest.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Request did not complete; outcome may be uncertain.');
Exit;
end;
if (rest.ResponseStatusCode <> 200) then
begin
Memo1.Lines.Add('HTTP status: ' + IntToStr(rest.ResponseStatusCode));
Memo1.Lines.Add('Azure error code: ' + rest.ResponseHdrByName('x-ms-error-code'));
Memo1.Lines.Add('Request ID: ' + rest.ResponseHdrByName('x-ms-request-id'));
// 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('',1);
if (sameText3 = 1) then
begin
Memo1.Lines.Add('Missing blob ETag.');
Exit;
end;
totalText := rest.ResponseHdrByName('Content-Length');
totalValue := TChilkatStringBuilder.Create(Self);
success := totalValue.Append(totalText);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
if ((totalValue.Length < 1) or (totalValue.Length > 10)) then
begin
Memo1.Lines.Add('Invalid or oversized length for this bounded example.');
Exit;
end;
totalDigits := TChilkatStringBuilder.Create(Self);
success := totalDigits.Append(totalText);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
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.Length <> 0) then
begin
Memo1.Lines.Add('Length must be a decimal string.');
Exit;
end;
if ((totalValue.Length = 10) and (totalValue.StartsWith('1',1) <> 1) and (totalValue.ContentsEqual('2000000000',1) <> 1)) then
begin
Memo1.Lines.Add('Length exceeds the 2,000,000,000-byte demonstration bound.');
Exit;
end;
totalNumber := TChilkatJsonObject.Create(Self);
success := totalNumber.UpdateNumber('value',totalText);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
total := totalNumber.IntOf('value');
checkpoint := TChilkatJsonObject.Create(Self);
checkpoint.Strict := 1;
if (files.FileExists(checkpointFile) = 1) then
begin
success := checkpoint.LoadFile(checkpointFile);
if (success <> 1) then
begin
Memo1.Lines.Add('Invalid checkpoint.');
Exit;
end;
textCompare.Clear();
textCompare.SetString(checkpoint.StringOf('path'));
sameText4 := textCompare.ContentsEqual(resourcePath,1);
textCompare.Clear();
textCompare.SetString(checkpoint.StringOf('etag'));
sameText5 := textCompare.ContentsEqual(etag,1);
textCompare.Clear();
textCompare.SetString(checkpoint.StringOf('size'));
sameText6 := textCompare.ContentsEqual(totalText,1);
if ((checkpoint.StringOf('account') <> config.StringOf('account')) or (sameText4 <> 1) or (sameText5 <> 1) or (sameText6 <> 1)) then
begin
Memo1.Lines.Add('The remote blob or checkpoint target changed. Preserve the old partial output and restart separately.');
Exit;
end;
end
else
begin
if (files.FileExists(partFile) = 1) then
begin
Memo1.Lines.Add('Partial file exists without its checkpoint; refusing to append.');
Exit;
end;
success := checkpoint.UpdateString('account',config.StringOf('account'));
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := checkpoint.UpdateString('path',resourcePath);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := checkpoint.UpdateString('etag',etag);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := checkpoint.UpdateString('size',totalText);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := checkpoint.WriteFile('qa_data/azure/download-checkpoint.tmp');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not write checkpoint.');
Exit;
end;
success := files.FileRename('qa_data/azure/download-checkpoint.tmp',checkpointFile);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not publish checkpoint.');
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) = 1) then
begin
localSize := files.FileSizeStr(partFile);
if (files.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not get partial-file size.');
Exit;
end;
end;
offsetText := localSize;
offsetValue := TChilkatStringBuilder.Create(Self);
success := offsetValue.Append(offsetText);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
if ((offsetValue.Length < 1) or (offsetValue.Length > 10)) then
begin
Memo1.Lines.Add('Invalid or oversized length for this bounded example.');
Exit;
end;
offsetDigits := TChilkatStringBuilder.Create(Self);
success := offsetDigits.Append(offsetText);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
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.Length <> 0) then
begin
Memo1.Lines.Add('Length must be a decimal string.');
Exit;
end;
if ((offsetValue.Length = 10) and (offsetValue.StartsWith('1',1) <> 1) and (offsetValue.ContentsEqual('2000000000',1) <> 1)) then
begin
Memo1.Lines.Add('Length exceeds the 2,000,000,000-byte demonstration bound.');
Exit;
end;
offsetNumber := TChilkatJsonObject.Create(Self);
success := offsetNumber.UpdateNumber('value',offsetText);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
offset := offsetNumber.IntOf('value');
if (offset > total) then
begin
Memo1.Lines.Add('Partial file is longer than the selected blob.');
Exit;
end;
// Ensure an empty blob also creates a local file.
success := files.OpenForAppend(partFile);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not open partial file.');
Exit;
end;
files.FileClose();
success := rest.AddHeader('If-Match',etag);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
chunk := TChilkatBinData.Create(Self);
range := TChilkatStringBuilder.Create(Self);
expectedRange := TChilkatStringBuilder.Create(Self);
expectedLength := TChilkatStringBuilder.Create(Self);
while (offset < total) do
begin
count := total - offset;
if (count > 4194304) then
begin
count := 4194304;
end;
endByte := offset + count - 1;
range.Clear();
success := range.Append('bytes=');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := range.AppendInt(offset);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := range.Append('-');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := range.AppendInt(endByte);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := rest.AddHeader('x-ms-range',range.GetAsString());
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
expectedRange.Clear();
success := expectedRange.Append('bytes ');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := expectedRange.AppendInt(offset);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := expectedRange.Append('-');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := expectedRange.AppendInt(endByte);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := expectedRange.Append('/');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := expectedRange.Append(totalText);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
expectedLength.Clear();
success := expectedLength.AppendInt(count);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
rest.Disconnect(10);
success := connection.Connect(endpoint.GetAsString(),443,1,20000);
if (success <> 1) then
begin
Memo1.Lines.Add('TLS reconnection failed.');
Exit;
end;
success := rest.UseConnection(connection.ControlInterface,0);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := rest.SendReqNoBody('GET',resourcePath);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
httpStatus := rest.ReadResponseHeader();
if (httpStatus < 0) then
begin
Memo1.Lines.Add('Could not read range response headers.');
Exit;
end;
if (rest.ResponseStatusCode <> 206) then
begin
Memo1.Lines.Add('HTTP status: ' + IntToStr(rest.ResponseStatusCode));
Memo1.Lines.Add('Azure error code: ' + rest.ResponseHdrByName('x-ms-error-code'));
Memo1.Lines.Add('Request ID: ' + rest.ResponseHdrByName('x-ms-request-id'));
// 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,1);
if ((sameText7 <> 1) or (rest.ResponseHdrByName('Content-Range') <> expectedRange.GetAsString()) or (rest.ResponseHdrByName('Content-Length') <> expectedLength.GetAsString())) then
begin
Memo1.Lines.Add('Unexpected range response; no bytes appended.');
Exit;
end;
success := chunk.Clear();
if (success <> 1) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := rest.ReadRespBd(chunk.ControlInterface);
if (success <> 1) then
begin
Memo1.Lines.Add('Incomplete range body; no bytes appended.');
Exit;
end;
if (chunk.NumBytes <> count) then
begin
Memo1.Lines.Add('Wrong byte count; no bytes appended.');
Exit;
end;
success := files.OpenForAppend(partFile);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not reopen partial file.');
Exit;
end;
success := files.FileWriteBd(chunk.ControlInterface,0,0);
files.FileClose();
if (success <> 1) then
begin
Memo1.Lines.Add('Local write failed. Inspect the partial file before retrying.');
Exit;
end;
offset := offset + count;
end;
success := files.FileRename(partFile,finalFile);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not publish completed download.');
Exit;
end;
Memo1.Lines.Add('Download complete. Retain or archive the checkpoint with the completed file.');