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

Amazon S3: Resume a Download with Range and If-Match

See more S3 - REST Examples

Resume an unchanged partial file using its original quoted ETag and total length, not metadata fetched after the failure. Save a private s3-download.json sidecar when starting: string fields bucket, key, region, etag (including quotes), and total_size. Use s3-download.part for that object only.

FileSizeStr avoids 32-bit overflow. The code appends only HTTP 206 with a matching ETag, Content-Range start and total size. A 200 response must never be appended; 412 means the validator failed, and 416 is not automatically success. Check final size, and verify an independently recorded checksum when needed. ETags are validators, not universally MD5 hashes. Concurrent local modification is outside this example.

For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.

Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.

Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.

AWS GetObject reference

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  var success = false;

  // StringBuilder compares text by value in every generated language.
  final textCompare = CkStringBuilder();
  // Assumes Chilkat is unlocked. See Global Unlock Sample.
  success = false;
  // Private configuration, not a file in public web content or source control.
  // Load current IAM credentials authorized for the S3 operation.
  final credentials = CkJsonObject();
  credentials.strict = true;
  try {
    credentials.loadFile('qa_data/aws/s3.json');
  } on ChilkatException {
    print('Could not load private AWS credentials.');
    return;
  }

  textCompare.clear();
  textCompare.setString(credentials.stringOf('access_key'));
  final sameText1 = textCompare.contentsEqual('', true);
  if ((credentials.jsonTypeOf('access_key') != 1) || (sameText1)) {
    print('Missing or invalid access_key.');
    return;
  }

  textCompare.clear();
  textCompare.setString(credentials.stringOf('secret_key'));
  final sameText2 = textCompare.contentsEqual('', true);
  if ((credentials.jsonTypeOf('secret_key') != 1) || (sameText2)) {
    print('Missing or invalid secret_key.');
    return;
  }

  // General purpose bucket in the commercial AWS partition.
  final region = 'us-west-2';
  final bucketName = 'amzn-s3-demo-bucket';
  final endpoint = CkStringBuilder();
  try {
    endpoint.append(bucketName);
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    endpoint.append('.');
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    endpoint.append('s3.');
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    endpoint.append(region);
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    endpoint.append('.amazonaws.com');
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  final aws = CkAuthAws();
  aws.accessKey = credentials.stringOf('access_key');
  aws.secretKey = credentials.stringOf('secret_key');
  aws.region = region;
  aws.serviceName = 's3';
  aws.signatureVersion = 4;
  final rest = CkRest();
  rest.connectTimeoutMs = 20000;
  rest.idleTimeoutMs = 60000;
  try {
    rest.setAuthAws(aws);
  } on ChilkatException {
    print('Could not configure AWS signing.');
    return;
  }

  // Temporary credentials require this token in every signed query.
  // Keep request URLs private. Do not clear this parameter between requests.
  if (credentials.hasMember('session_token')) {
    if (credentials.jsonTypeOf('session_token') != 1) {
      print('session_token must be a string.');
      return;
    }

    textCompare.clear();
    textCompare.setString(credentials.stringOf('session_token'));
    final sameText3 = textCompare.contentsEqual('', true);
    if (!sameText3) {
      try {
        rest.addQueryParam('X-Amz-Security-Token', credentials.stringOf('session_token'));
      } on ChilkatException {
        print('Could not prepare the request.');
        return;
      }
    }
  }

  // Connect to the SAME hostname used for TLS verification and request signing.
  final connection = CkSocket();
  connection.requireSslCertVerify = true;
  connection.maxReadIdleMs = 60000;
  connection.maxSendIdleMs = 60000;
  try {
    connection.connect(endpoint.getAsString(), 443, true, 20000);
  } on ChilkatException {
    print('TLS connection failed; inspect diagnostics privately.');
    return;
  }

  try {
    rest.useConnection(connection, true);
  } on ChilkatException {
    print('Could not attach the TLS connection.');
    return;
  }

  final xml = CkXml();
  xml.strict = true;
  // Supply an unencoded object key, not a URL. Preserve slashes in the key.
  final objectKey = 'documents/example.txt';
  final objectPath = CkStringBuilder();
  try {
    objectPath.append(objectKey);
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    objectPath.encode('url_rfc3986', 'utf-8');
  } on ChilkatException {
    print('Could not encode the object key.');
    return;
  }

  final restoredSlashes = objectPath.replace('%2F', '/');
  try {
    objectPath.prepend('/');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  // The sidecar must describe the SAME partial file and original object.
  // Save its exact quoted ETag and full Content-Length when starting the download.
  final checkpoint = CkJsonObject();
  checkpoint.strict = true;
  try {
    checkpoint.loadFile('s3-download.json');
  } on ChilkatException {
    print('Could not load the download checkpoint.');
    return;
  }

  textCompare.clear();
  textCompare.setString(checkpoint.stringOf('bucket'));
  final sameText4 = textCompare.contentsEqual('', true);
  if ((checkpoint.jsonTypeOf('bucket') != 1) || (sameText4)) {
    print('Invalid checkpoint field: bucket');
    return;
  }

  textCompare.clear();
  textCompare.setString(checkpoint.stringOf('key'));
  final sameText5 = textCompare.contentsEqual('', true);
  if ((checkpoint.jsonTypeOf('key') != 1) || (sameText5)) {
    print('Invalid checkpoint field: key');
    return;
  }

  textCompare.clear();
  textCompare.setString(checkpoint.stringOf('region'));
  final sameText6 = textCompare.contentsEqual('', true);
  if ((checkpoint.jsonTypeOf('region') != 1) || (sameText6)) {
    print('Invalid checkpoint field: region');
    return;
  }

  textCompare.clear();
  textCompare.setString(checkpoint.stringOf('etag'));
  final sameText7 = textCompare.contentsEqual('', true);
  if ((checkpoint.jsonTypeOf('etag') != 1) || (sameText7)) {
    print('Invalid checkpoint field: etag');
    return;
  }

  textCompare.clear();
  textCompare.setString(checkpoint.stringOf('total_size'));
  final sameText8 = textCompare.contentsEqual('', true);
  if ((checkpoint.jsonTypeOf('total_size') != 1) || (sameText8)) {
    print('Invalid checkpoint field: total_size');
    return;
  }

  textCompare.clear();
  textCompare.setString(checkpoint.stringOf('bucket'));
  final sameText9 = textCompare.contentsEqual(bucketName, true);
  textCompare.clear();
  textCompare.setString(checkpoint.stringOf('key'));
  final sameText10 = textCompare.contentsEqual(objectKey, true);
  textCompare.clear();
  textCompare.setString(checkpoint.stringOf('region'));
  final sameText11 = textCompare.contentsEqual(region, true);
  if ((!sameText9) || ((!sameText10) || (!sameText11))) {
    print('Checkpoint does not match this object.');
    return;
  }

  final files = CkFileAccess();
  final String localSize;
  try {
    localSize = files.fileSizeStr('s3-download.part');
  } on ChilkatException {
    print('Could not determine the partial file size.');
    return;
  }

  textCompare.clear();
  textCompare.setString(localSize);
  final sameText12 = textCompare.contentsEqual(checkpoint.stringOf('total_size'), true);
  if (sameText12) {
    print('Local length already matches the checkpoint; verify integrity before publishing.');
    return;
  }

  final range = CkStringBuilder();
  try {
    range.append('bytes=');
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    range.append(localSize);
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    range.append('-');
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    rest.addHeader('Range', range.getAsString());
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    rest.addHeader('If-Match', checkpoint.stringOf('etag'));
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    rest.sendReqNoBody('GET', objectPath.getAsString());
  } on ChilkatException {
    print('Could not send download request.');
    return;
  }

  final statusCode = rest.readResponseHeader();
  if (statusCode < 0) {
    print('Could not read download headers.');
    return;
  }

  if (statusCode != 206) {
    print('Download HTTP status: $statusCode');
    try {
      final errorBody = rest.readRespBodyString();
      success = true;
      try {
        xml.loadXml(errorBody);
      } on ChilkatException {
        success = false;
      }
      textCompare.clear();
      textCompare.setString(xml.tag);
      final sameText13 = textCompare.contentsEqual('Error', true);
      if ((success) && (sameText13)) {
        print('S3 error code: ${xml.getChildContent('Code')}');
      }
    } on ChilkatException {
      // rest.readRespBodyString() failed; continue anyway.
    }

    return;
  }

  // Never append HTTP 200, 412, or 416 to the existing file.
  final returnedEtag = rest.responseHdrByName('ETag');
  textCompare.clear();
  textCompare.setString(returnedEtag);
  final sameText14 = textCompare.contentsEqual(checkpoint.stringOf('etag'), true);
  if ((!rest.lastMethodSuccess) || (!sameText14)) {
    print('Object validator changed; partial file was not modified.');
    return;
  }

  final contentRange = CkStringBuilder();
  try {
    contentRange.append(rest.responseHdrByName('Content-Range'));
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  final expectedStart = CkStringBuilder();
  try {
    expectedStart.append('bytes ');
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    expectedStart.append(localSize);
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    expectedStart.append('-');
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  if (!contentRange.startsWith(expectedStart.getAsString(), true)) {
    print('Range start does not match the partial file.');
    return;
  }

  final expectedTotal = CkStringBuilder();
  try {
    expectedTotal.append('/');
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    expectedTotal.append(checkpoint.stringOf('total_size'));
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  if (!contentRange.endsWith(expectedTotal.getAsString(), true)) {
    print('Object length changed; partial file was not modified.');
    return;
  }

  // The file must be an unchanged prefix of the object; size alone cannot prove that.
  final output = CkStream();
  output.sinkFile = 's3-download.part';
  output.sinkFileAppend = true;
  try {
    rest.readRespBodyStream(output, true);
  } on ChilkatException {
    print('Resume incomplete; retain the partial file and original checkpoint.');
    return;
  }

  final finalSize = files.fileSizeStr('s3-download.part');
  textCompare.clear();
  textCompare.setString(finalSize);
  final sameText15 = textCompare.contentsEqual(checkpoint.stringOf('total_size'), true);
  if ((!files.lastMethodSuccess) || (!sameText15)) {
    print('Result length does not match the original full object.');
    return;
  }

  print('Resumed download complete.');
}