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

Amazon S3: Complete a Multipart Upload and Check Embedded Errors

See more S3 - REST Examples

Submit the ascending part numbers and exact ETags recorded by the parts example. Requires s3:PutObject. The server may send whitespace while finishing. HTTP 200 alone is insufficient: an Error XML response can follow those headers. This example consumes and validates the complete response before reporting success.

If the connection fails or a retry returns NoSuchUpload, inspect the final object before starting over; the original completion may have succeeded. A multipart ETag is not a general MD5 checksum of the full object.

Part of the initiate / upload parts / complete workflow. State in s3-multipart.json binds the upload ID to its bucket, region and key. Keep it private. Incomplete parts incur storage charges until completed or aborted; configure an AbortIncompleteMultipartUpload lifecycle rule as cleanup protection. These examples use the default checksum behavior without selecting a separate composite checksum algorithm. If you choose one at initiation, store each required part checksum and supply it at completion.

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 CompleteMultipartUpload 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;
  final state = CkJsonObject();
  state.strict = true;
  try {
    state.loadFile('s3-multipart.json');
  } on ChilkatException {
    print('Could not load multipart state.');
    return;
  }

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

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

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

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

  textCompare.clear();
  textCompare.setString(state.stringOf('bucket'));
  final sameText8 = textCompare.contentsEqual(bucketName, true);
  textCompare.clear();
  textCompare.setString(state.stringOf('region'));
  final sameText9 = textCompare.contentsEqual(region, true);
  if ((!sameText8) || (!sameText9)) {
    print('Multipart state belongs to another bucket or region.');
    return;
  }

  final uploadId = state.stringOf('upload_id');
  // Supply an unencoded object key, not a URL. Preserve slashes in the key.
  final objectKey = state.stringOf('key');
  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;
  }

  if (state.jsonTypeOf('completion_xml') != 1) {
    print('Upload all parts before completing.');
    return;
  }

  final parts = CkXml();
  parts.strict = true;
  try {
    parts.loadXml(state.stringOf('completion_xml'));
  } on ChilkatException {
    print('Invalid saved completion XML.');
    return;
  }

  textCompare.clear();
  textCompare.setString(parts.tag);
  final sameText10 = textCompare.contentsEqual('CompleteMultipartUpload', true);
  if ((!sameText10) || (parts.numChildren < 1)) {
    print('Invalid saved completion parts.');
    return;
  }

  var i = 0;
  while (i < parts.numChildren) {
    parts.i = i;
    if (parts.getChildIntValue('Part[i]|PartNumber') != i + 1) {
      print('Completion part numbers must be consecutive and ascending.');
      return;
    }

    textCompare.clear();
    textCompare.setString(parts.getChildContent('Part[i]|ETag'));
    final sameText11 = textCompare.contentsEqual('', true);
    if ((!parts.hasChildWithTag('Part[i]|ETag')) || (sameText11)) {
      print('Completion part ETag is missing.');
      return;
    }

    i++;
  }

  try {
    rest.addQueryParam('uploadId', uploadId);
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    rest.addHeader('Content-Type', 'application/xml');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  final String responseBody;
  try {
    responseBody = rest.fullRequestString('POST', objectPath.getAsString(), parts.getXml());
  } on ChilkatException {
    print('Request did not complete; inspect diagnostics privately.');
    return;
  }

  if (rest.responseStatusCode != 200) {
    print('S3 HTTP status: ${rest.responseStatusCode}');
    success = true;
    try {
      xml.loadXml(responseBody);
    } on ChilkatException {
      success = false;
    }
    textCompare.clear();
    textCompare.setString(xml.tag);
    final sameText12 = textCompare.contentsEqual('Error', true);
    if ((success) && (sameText12)) {
      print('S3 error code: ${xml.getChildContent('Code')}');
    }

    // Keep signed headers, credentials, URLs, and full diagnostics private.
    // A timeout may leave a write's outcome uncertain. Check before retrying.
    return;
  }

  // S3 can return an Error XML body inside HTTP 200. Check the root too.
  try {
    xml.loadXml(responseBody);
  } on ChilkatException {
    print('Expected well-formed XML.');
    return;
  }

  textCompare.clear();
  textCompare.setString(xml.tag);
  final sameText13 = textCompare.contentsEqual('CompleteMultipartUploadResult', true);
  if (!sameText13) {
    print('Unexpected S3 response element; this is not a successful result.');
    return;
  }

  textCompare.clear();
  textCompare.setString(xml.getChildContent('ETag'));
  final sameText14 = textCompare.contentsEqual('', true);
  if ((!xml.hasChildWithTag('ETag')) || (sameText14)) {
    print('Missing response field: ETag');
    return;
  }

  print('Multipart upload completed.');
  print('Object ETag: ${xml.getChildContent('ETag')}');
  // Archive the state now; an uncertain retry may return NoSuchUpload even after success.
}