Sample code for 30+ languages & platforms
CkJava 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 CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  StringBuilder compares text by value in every generated language.
    CkStringBuilder textCompare = new CkStringBuilder();
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;
    CkJsonObject config = new CkJsonObject();
    config.put_Strict(true);
    success = config.LoadFile("qa_data/azure/storage.json");
    if (success != true) {
        System.out.println("Could not load private Azure configuration.");
        return;
        }

    textCompare.Clear();
    textCompare.SetString(config.stringOf("account"));
    boolean sameText1 = textCompare.ContentsEqual("",true);
    if ((config.JsonTypeOf("account") != 1) || (sameText1 == true)) {
        System.out.println("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"));
    boolean sameText2 = textCompare.ContentsEqual("",true);
    if ((config.JsonTypeOf("access_key") != 1) || (sameText2 == true)) {
        System.out.println("Supply the base64 account access key.");
        return;
        }

    CkStringBuilder endpoint = new CkStringBuilder();
    success = endpoint.Append(config.stringOf("account"));
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    success = endpoint.Append(".blob.core.windows.net");
    if (success != true) {
        System.out.println("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.
    String resourcePath = "/examplecontainer/example.bin";
    CkRest rest = new CkRest();
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    CkAuthAzureStorage azAuth = new CkAuthAzureStorage();
    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) {
        System.out.println("Could not configure Shared Key signing.");
        return;
        }

    CkSocket connection = new CkSocket();
    connection.put_RequireSslCertVerify(true);
    connection.put_MaxReadIdleMs(60000);
    connection.put_MaxSendIdleMs(60000);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        System.out.println("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) {
        System.out.println("Could not prepare the request.");
        return;
        }

    String responseText;
    CkStringBuilder responseBody = new CkStringBuilder();
    CkXml result = new CkXml();
    result.put_Strict(true);
    String sourceFile = "qa_data/bin/sample.bin";
    String checkpointFile = "qa_data/azure/upload-checkpoint.json";
    CkFileAccess input = new CkFileAccess();
    success = input.OpenForRead(sourceFile);
    if (success != true) {
        System.out.println("Could not open upload source.");
        input.FileClose();
        return;
        }

    String sourceSize = input.fileSizeStr(sourceFile);
    if (input.get_LastMethodSuccess() != true) {
        System.out.println("Could not read source size.");
        input.FileClose();
        return;
        }

    int blockSize = 4194304;
    int numBlocks = input.GetNumBlocks(blockSize);
    if ((input.get_LastMethodSuccess() != true) || (numBlocks < 0) || (numBlocks > 50000)) {
        System.out.println("Source exceeds the 50,000-block demonstration bound.");
        input.FileClose();
        return;
        }

    CkCrypt2 hash = new CkCrypt2();
    hash.put_HashAlgorithm("sha256");
    hash.put_EncodingMode("hex_lower");
    String fingerprint = hash.hashFileENC(sourceFile);
    if (hash.get_LastMethodSuccess() != true) {
        System.out.println("Could not fingerprint source.");
        input.FileClose();
        return;
        }

    CkJsonObject checkpoint = new CkJsonObject();
    checkpoint.put_Strict(true);
    CkFileAccess files = new CkFileAccess();
    if (files.FileExists(checkpointFile) == true) {
        success = checkpoint.LoadFile(checkpointFile);
        if (success != true) {
            System.out.println("Invalid checkpoint; do not silently start another upload.");
            input.FileClose();
            return;
            }

        textCompare.Clear();
        textCompare.SetString(checkpoint.stringOf("path"));
        boolean sameText3 = textCompare.ContentsEqual(resourcePath,true);
        textCompare.Clear();
        textCompare.SetString(checkpoint.stringOf("sha256"));
        boolean sameText4 = textCompare.ContentsEqual(fingerprint,true);
        textCompare.Clear();
        textCompare.SetString(checkpoint.stringOf("size"));
        boolean sameText5 = textCompare.ContentsEqual(sourceSize,true);
        if ((checkpoint.stringOf("account") != config.stringOf("account")) || (sameText3 != true) || (sameText4 != true) || (sameText5 != true) || (checkpoint.IntOf("block_size") != blockSize)) {
            System.out.println("Checkpoint target or source changed. Choose a new checkpoint/target deliberately.");
            input.FileClose();
            return;
            }

        textCompare.Clear();
        textCompare.SetString(checkpoint.stringOf("upload_id"));
        boolean sameText6 = textCompare.ContentsEqual("",true);
        if (sameText6 == true) {
            System.out.println("Missing checkpoint upload ID.");
            input.FileClose();
            return;
            }

        }
    else {
        String newId = hash.generateUuid();
        if (hash.get_LastMethodSuccess() != true) {
            System.out.println("Could not generate upload ID.");
            input.FileClose();
            return;
            }

        success = checkpoint.UpdateString("account",config.stringOf("account"));
        if (success != true) {
            System.out.println("Could not prepare the request.");
            input.FileClose();
            return;
            }

        success = checkpoint.UpdateString("path",resourcePath);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            input.FileClose();
            return;
            }

        success = checkpoint.UpdateString("sha256",fingerprint);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            input.FileClose();
            return;
            }

        success = checkpoint.UpdateString("size",sourceSize);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            input.FileClose();
            return;
            }

        success = checkpoint.UpdateInt("block_size",blockSize);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            input.FileClose();
            return;
            }

        success = checkpoint.UpdateString("upload_id",newId);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            input.FileClose();
            return;
            }

        success = checkpoint.WriteFile("qa_data/azure/upload-checkpoint.tmp");
        if (success != true) {
            System.out.println("Could not write checkpoint.");
            input.FileClose();
            return;
            }

        success = files.FileRename("qa_data/azure/upload-checkpoint.tmp",checkpointFile);
        if (success != true) {
            System.out.println("Could not publish checkpoint.");
            input.FileClose();
            return;
            }

        }

    String uploadId = checkpoint.stringOf("upload_id");
    CkStringBuilder idCheck = new CkStringBuilder();
    success = idCheck.Append(uploadId);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        input.FileClose();
        return;
        }

    if (idCheck.get_Length() != 36) {
        System.out.println("Invalid upload ID length in checkpoint.");
        input.FileClose();
        return;
        }

    //  Reconcile an uncertain commit before staging anything else.
    responseText = rest.fullRequestNoBody("HEAD",resourcePath);
    if (rest.get_LastMethodSuccess() != true) {
        System.out.println("Could not inspect destination.");
        input.FileClose();
        return;
        }

    if (rest.get_ResponseStatusCode() == 200) {
        textCompare.Clear();
        textCompare.SetString(rest.responseHdrByName("x-ms-meta-upload-id"));
        boolean sameText7 = textCompare.ContentsEqual(uploadId,true);
        textCompare.Clear();
        textCompare.SetString(rest.responseHdrByName("x-ms-meta-source-sha256"));
        boolean sameText8 = textCompare.ContentsEqual(fingerprint,true);
        textCompare.Clear();
        textCompare.SetString(rest.responseHdrByName("Content-Length"));
        boolean sameText9 = textCompare.ContentsEqual(sourceSize,true);
        if ((sameText7 != true) || (sameText8 != true) || (sameText9 != true)) {
            System.out.println("Destination exists and is not this completed upload. Refusing to replace it.");
            input.FileClose();
            return;
            }

        System.out.println("Upload already committed. Keep the checkpoint until the application records completion.");
        input.FileClose();
        return;
        }

    textCompare.Clear();
    textCompare.SetString(rest.responseHdrByName("x-ms-error-code"));
    boolean sameText10 = textCompare.ContentsEqual("BlobNotFound",true);
    if ((rest.get_ResponseStatusCode() != 404) || (sameText10 != true)) {
        System.out.println("Expected an absent blob in an existing container.");
        input.FileClose();
        return;
        }

    success = rest.AddQueryParam("comp","blocklist");
    if (success != true) {
        System.out.println("Could not prepare the request.");
        input.FileClose();
        return;
        }

    success = rest.AddQueryParam("blocklisttype","uncommitted");
    if (success != true) {
        System.out.println("Could not prepare the request.");
        input.FileClose();
        return;
        }

    rest.Disconnect(10);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        System.out.println("TLS reconnection failed.");
        input.FileClose();
        return;
        }

    success = rest.UseConnection(connection,false);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        input.FileClose();
        return;
        }

    responseText = rest.fullRequestNoBody("GET",resourcePath);
    if (rest.get_LastMethodSuccess() != true) {
        System.out.println("Could not reconcile uploaded blocks.");
        input.FileClose();
        return;
        }

    CkHashtable remoteBlocks = new CkHashtable();
    if (rest.get_ResponseStatusCode() == 200) {
        success = result.LoadXml(responseText);
        if (success != true) {
            System.out.println("Expected well-formed XML.");
            input.FileClose();
            return;
            }

        if (result.TagEquals("BlockList") != true) {
            System.out.println("Unexpected XML response root.");
            input.FileClose();
            return;
            }

        int remoteCount = result.NumChildrenAt("UncommittedBlocks");
        int j = 0;
        while ((j < remoteCount)) {
            result.put_I(j);
            String remoteId = result.getChildContent("UncommittedBlocks|Block[i]|Name");
            String remoteSize = result.getChildContent("UncommittedBlocks|Block[i]|Size");
            textCompare.Clear();
            textCompare.SetString(remoteId);
            boolean sameText11 = textCompare.ContentsEqual("",true);
            textCompare.Clear();
            textCompare.SetString(remoteSize);
            boolean sameText12 = textCompare.ContentsEqual("",true);
            if ((sameText11 == true) || (sameText12 == true)) {
                System.out.println("Malformed remote block listing.");
                input.FileClose();
                return;
                }

            success = remoteBlocks.AddStr(remoteId,remoteSize);
            if (success != true) {
                System.out.println("Could not prepare the request.");
                input.FileClose();
                return;
                }

            j = j+1;
            }

        }
    else {
        textCompare.Clear();
        textCompare.SetString(rest.responseHdrByName("x-ms-error-code"));
        boolean sameText13 = textCompare.ContentsEqual("BlobNotFound",true);
        if ((rest.get_ResponseStatusCode() != 404) || (sameText13 != true)) {
            System.out.println("Block listing failed.");
            input.FileClose();
            return;
            }

        }

    CkXml blocks = new CkXml();
    blocks.put_Tag("BlockList");
    CkBinData chunk = new CkBinData();
    CkStringBuilder blockText = new CkStringBuilder();
    CkStringBuilder sizeText = new CkStringBuilder();
    int i = 0;
    while ((i < numBlocks)) {
        success = chunk.Clear();
        if (success != true) {
            System.out.println("Could not prepare the request.");
            input.FileClose();
            return;
            }

        success = input.ReadBlockBd(i,blockSize,chunk);
        if (success != true) {
            System.out.println("Could not read source block.");
            input.FileClose();
            return;
            }

        if ((chunk.get_NumBytes() < 1) || ((i < numBlocks - 1) && (chunk.get_NumBytes() != blockSize))) {
            System.out.println("Source changed or an incomplete read occurred.");
            input.FileClose();
            return;
            }

        blockText.Clear();
        success = blockText.Append(uploadId);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            input.FileClose();
            return;
            }

        success = blockText.Append(input.genBlockId(i,5,"ascii"));
        if (success != true) {
            System.out.println("Could not prepare the request.");
            input.FileClose();
            return;
            }

        success = blockText.Encode("base64","utf-8");
        if (success != true) {
            System.out.println("Could not prepare the request.");
            input.FileClose();
            return;
            }

        String blockId = blockText.getAsString();
        sizeText.Clear();
        success = sizeText.AppendInt(chunk.get_NumBytes());
        if (success != true) {
            System.out.println("Could not prepare the request.");
            input.FileClose();
            return;
            }

        boolean uploadBlock = true;
        if (remoteBlocks.Contains(blockId) == true) {
            if (remoteBlocks.lookupStr(blockId) != sizeText.getAsString()) {
                System.out.println("Remote block size differs; do not commit this upload.");
                input.FileClose();
                return;
                }

            uploadBlock = false;
            }

        if (uploadBlock == true) {
            success = rest.ClearAllQueryParams();
            if (success != true) {
                System.out.println("Could not prepare the request.");
                input.FileClose();
                return;
                }

            success = rest.AddQueryParam("comp","block");
            if (success != true) {
                System.out.println("Could not prepare the request.");
                input.FileClose();
                return;
                }

            success = rest.AddQueryParam("blockid",blockId);
            if (success != true) {
                System.out.println("Could not prepare the request.");
                input.FileClose();
                return;
                }

            rest.Disconnect(10);
            success = connection.Connect(endpoint.getAsString(),443,true,20000);
            if (success != true) {
                System.out.println("TLS reconnection failed.");
                input.FileClose();
                return;
                }

            success = rest.UseConnection(connection,false);
            if (success != true) {
                System.out.println("Could not prepare the request.");
                input.FileClose();
                return;
                }

            responseBody.Clear();
            success = rest.FullRequestBd("PUT",resourcePath,chunk,responseBody);
            if (success != true) {
                System.out.println("Request did not complete; outcome may be uncertain.");
                input.FileClose();
                return;
                }

            if (rest.get_ResponseStatusCode() != 201) {
                System.out.println("HTTP status: " + rest.get_ResponseStatusCode());
                System.out.println("Azure error code: " + rest.responseHdrByName("x-ms-error-code"));
                System.out.println("Request ID: " + rest.responseHdrByName("x-ms-request-id"));
                //  Inspect any error body privately; do not log credentials, SAS URLs or payloads.
                input.FileClose();
                return;
                }

            }

        blocks.NewChild2("Uncommitted",blockId);
        i = i+1;
        }

    //  Rehash before commit. Do not modify the source or run concurrent writers.
    String finalFingerprint = hash.hashFileENC(sourceFile);
    textCompare.Clear();
    textCompare.SetString(finalFingerprint);
    boolean sameText14 = textCompare.ContentsEqual(fingerprint,true);
    if ((hash.get_LastMethodSuccess() != true) || (sameText14 != true)) {
        System.out.println("Source changed during staging; commit cancelled.");
        input.FileClose();
        return;
        }

    input.FileClose();
    success = rest.ClearAllQueryParams();
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    success = rest.AddQueryParam("comp","blocklist");
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    success = rest.AddHeader("Content-Type","application/xml");
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    success = rest.AddHeader("x-ms-blob-content-type","application/octet-stream");
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    success = rest.AddHeader("If-None-Match","*");
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    success = rest.AddHeader("x-ms-meta-upload-id",uploadId);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    success = rest.AddHeader("x-ms-meta-source-sha256",fingerprint);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    rest.Disconnect(10);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        System.out.println("TLS reconnection failed.");
        return;
        }

    success = rest.UseConnection(connection,false);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    responseText = rest.fullRequestString("PUT",resourcePath,blocks.getXml());
    if (rest.get_LastMethodSuccess() != true) {
        System.out.println("Request did not complete; outcome may be uncertain.");
        return;
        }

    if (rest.get_ResponseStatusCode() != 201) {
        System.out.println("HTTP status: " + rest.get_ResponseStatusCode());
        System.out.println("Azure error code: " + rest.responseHdrByName("x-ms-error-code"));
        System.out.println("Request ID: " + rest.responseHdrByName("x-ms-request-id"));
        //  Inspect any error body privately; do not log credentials, SAS URLs or payloads.
        return;
        }

    System.out.println("Upload committed. Retain the checkpoint for reconciliation until completion is recorded.");
  }
}