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

Amazon S3: Copy an Object Using Multipart Copy

See more S3 - REST Examples

Copy an object inside a general purpose bucket without downloading it. Initiate a destination upload, issue UploadPartCopy ranges, and complete it with the exact returned ETags. Requires source read and destination write permissions, plus applicable KMS permissions. HTTP 200 copy/completion bodies are checked for embedded errors.

The example uses 1,000,000,000-byte parts and supports objects larger than 5 MiB through 10,000,000,000,000 bytes (10 TB), with up to 10,000 parts. Decimal-string offset construction avoids int64 and 32-bit overflow. This is an example limit, not S3’s maximum object size; larger objects require larger parts. Only the final part may be below 5 MiB.

A source version is pinned when returned by HEAD, and every part uses the original ETag condition. Choose a distinct destination key; completing can replace that key or create a new version. Metadata and tags are not automatically inherited by multipart initiation; set the desired destination metadata, content type and encryption there. The source remains unchanged.

The saved s3-multipart.json can be used with the existing abort example after a failure. Completion XML is saved only after all copy parts succeed. Do not restart into the same state file blindly; an uncertain initiation/completion needs inspection. This example does not implement selective resume, and incomplete parts incur charges until completed or aborted.

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 UploadPartCopy reference

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
textCompare: HCkStringBuilder;
credentials: HCkJsonObject;
sameText1: Boolean;
sameText2: Boolean;
region: PWideChar;
bucketName: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
sameText3: Boolean;
connection: HCkSocket;
xml: HCkXml;
objectKey: PWideChar;
objectPath: HCkStringBuilder;
restoredSlashes: Integer;
statusCode: Integer;
sourceEtag: PWideChar;
sameText4: Boolean;
sourceSize: PWideChar;
sameText5: Boolean;
sourceVersion: PWideChar;
sizeText: HCkStringBuilder;
digits: HCkStringBuilder;
piece: HCkStringBuilder;
position: Integer;
digit: PWideChar;
fullBillions: Integer;
tailBytes: Integer;
numParts: Integer;
files: HCkFileAccess;
copySource: HCkStringBuilder;
sameText6: Boolean;
encodedVersion: HCkStringBuilder;
destinationKey: PWideChar;
sameText7: Boolean;
destinationSlashes: Integer;
responseBody: PWideChar;
sameText8: Boolean;
sameText9: Boolean;
sameText10: Boolean;
uploadId: PWideChar;
state: HCkJsonObject;
parts: HCkXml;
range: HCkStringBuilder;
ending: HCkStringBuilder;
number: HCkStringBuilder;
partNumber: Integer;
sameText11: Boolean;
sameText12: Boolean;
sameText13: Boolean;
sameText14: Boolean;
sameText15: Boolean;
sameText16: Boolean;

begin
success := False;

//  StringBuilder compares text by value in every generated language.
textCompare := CkStringBuilder_Create();
//  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.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/s3.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private AWS credentials.');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkJsonObject__stringOf(credentials,'access_key'));
sameText1 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (sameText1 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid access_key.');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkJsonObject__stringOf(credentials,'secret_key'));
sameText2 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (sameText2 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid secret_key.');
    Exit;
  end;
//  General purpose bucket in the commercial AWS partition.
region := 'us-west-2';
bucketName := 'amzn-s3-demo-bucket';
endpoint := CkStringBuilder_Create();
success := CkStringBuilder_Append(endpoint,bucketName);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Append(endpoint,'.');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Append(endpoint,'s3.');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Append(endpoint,region);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Append(endpoint,'.amazonaws.com');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(credentials,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(credentials,'secret_key'));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'s3');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not configure AWS signing.');
    Exit;
  end;
//  Temporary credentials require this token in every signed query.
//  Keep request URLs private. Do not clear this parameter between requests.
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
  begin
    if (CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) then
      begin
        Memo1.Lines.Add('session_token must be a string.');
        Exit;
      end;
    CkStringBuilder_Clear(textCompare);
    CkStringBuilder_SetString(textCompare,CkJsonObject__stringOf(credentials,'session_token'));
    sameText3 := CkStringBuilder_ContentsEqual(textCompare,'',True);
    if (sameText3 <> True) then
      begin
        success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',CkJsonObject__stringOf(credentials,'session_token'));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not prepare the request.');
            Exit;
          end;
      end;
  end;
//  Connect to the SAME hostname used for TLS verification and request signing.
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
  begin
    Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
    Exit;
  end;
success := CkRest_UseConnection(rest,connection,True);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not attach the TLS connection.');
    Exit;
  end;
xml := CkXml_Create();
CkXml_putStrict(xml,True);
//  Supply an unencoded object key, not a URL. Preserve slashes in the key.
objectKey := 'documents/source.bin';
objectPath := CkStringBuilder_Create();
success := CkStringBuilder_Append(objectPath,objectKey);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Encode(objectPath,'url_rfc3986','utf-8');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not encode the object key.');
    Exit;
  end;
restoredSlashes := CkStringBuilder_Replace(objectPath,'%2F','/');
success := CkStringBuilder_Prepend(objectPath,'/');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkRest_SendReqNoBody(rest,'HEAD',CkStringBuilder__getAsString(objectPath));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not send HEAD request.');
    Exit;
  end;
statusCode := CkRest_ReadResponseHeader(rest);
if (statusCode < 0) then
  begin
    Memo1.Lines.Add('Could not read the response header.');
    Exit;
  end;
if (statusCode <> 200) then
  begin
    Memo1.Lines.Add('HEAD did not return HTTP 200. A 403 is not proof that an object is missing.');
    Exit;
  end;
//  HEAD has no response body; do not call a body-reading method.
sourceEtag := CkRest__responseHdrByName(rest,'ETag');
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,sourceEtag);
sameText4 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkRest_getLastMethodSuccess(rest) <> True) or (sameText4 = True)) then
  begin
    Memo1.Lines.Add('Missing response header: ETag');
    Exit;
  end;
sourceSize := CkRest__responseHdrByName(rest,'Content-Length');
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,sourceSize);
sameText5 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkRest_getLastMethodSuccess(rest) <> True) or (sameText5 = True)) then
  begin
    Memo1.Lines.Add('Missing response header: Content-Length');
    Exit;
  end;
sourceVersion := CkRest__responseHdrByName(rest,'x-amz-version-id');
if (CkRest_getLastMethodSuccess(rest) <> True) then
  begin
    sourceVersion := '';
  end;
//  Split a decimal size into billions and a remainder. No large integer type.
sizeText := CkStringBuilder_Create();
digits := CkStringBuilder_Create();
piece := CkStringBuilder_Create();
success := CkStringBuilder_Append(sizeText,sourceSize);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Append(digits,'0123456789');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
if ((CkStringBuilder_getLength(sizeText) < 1) or (CkStringBuilder_getLength(sizeText) > 14)) then
  begin
    Memo1.Lines.Add('Invalid source length for this example.');
    Exit;
  end;
position := 0;
while (position < CkStringBuilder_getLength(sizeText)) do
  begin
    digit := CkStringBuilder__getRange(sizeText,position,1,False);
    if (CkStringBuilder_Contains(digits,digit,True) <> True) then
      begin
        Memo1.Lines.Add('Source length is not decimal.');
        Exit;
      end;
    position := position + 1;
  end;

fullBillions := 0;
tailBytes := 0;
if (CkStringBuilder_getLength(sizeText) > 9) then
  begin
    success := CkStringBuilder_SetString(piece,CkStringBuilder__getRange(sizeText,0,CkStringBuilder_getLength(sizeText) - 9,False));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not prepare the request.');
        Exit;
      end;
    fullBillions := CkStringBuilder_getIntValue(piece);
    success := CkStringBuilder_SetString(piece,CkStringBuilder__getRange(sizeText,CkStringBuilder_getLength(sizeText) - 9,9,False));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not prepare the request.');
        Exit;
      end;
    tailBytes := CkStringBuilder_getIntValue(piece);
  end
else
  begin
    tailBytes := CkStringBuilder_getIntValue(sizeText);
  end;
numParts := fullBillions;
if (tailBytes > 0) then
  begin
    numParts := numParts + 1;
  end;
if ((numParts < 1) or (numParts > 10000)) then
  begin
    Memo1.Lines.Add('This example supports objects through 10 TB using 1 GB parts.');
    Exit;
  end;
if ((fullBillions = 0) and (tailBytes <= 5242880)) then
  begin
    Memo1.Lines.Add('Use CopyObject for sources of 5 MiB or less; ranged copy requires a larger source.');
    Exit;
  end;
files := CkFileAccess_Create();
if (CkFileAccess_FileExists(files,'s3-multipart.json') = True) then
  begin
    Memo1.Lines.Add('A multipart state file already exists; finish or abort that upload first.');
    Exit;
  end;
copySource := CkStringBuilder_Create();
success := CkStringBuilder_Append(copySource,'/');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Append(copySource,bucketName);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Append(copySource,CkStringBuilder__getAsString(objectPath));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,sourceVersion);
sameText6 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if (sameText6 <> True) then
  begin
    encodedVersion := CkStringBuilder_Create();
    success := CkStringBuilder_Append(encodedVersion,sourceVersion);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not build text.');
        Exit;
      end;
    success := CkStringBuilder_Encode(encodedVersion,'url_rfc3986','utf-8');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not prepare the request.');
        Exit;
      end;
    success := CkStringBuilder_Append(copySource,'?versionId=');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not build text.');
        Exit;
      end;
    success := CkStringBuilder_Append(copySource,CkStringBuilder__getAsString(encodedVersion));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not build text.');
        Exit;
      end;
  end;
//  Destination is a DIFFERENT key in this bucket. Existing destination is replaced.
destinationKey := 'documents/copy.bin';
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,destinationKey);
sameText7 := CkStringBuilder_ContentsEqual(textCompare,objectKey,True);
if (sameText7 = True) then
  begin
    Memo1.Lines.Add('Choose a destination key different from the source.');
    Exit;
  end;
success := CkStringBuilder_SetString(objectPath,destinationKey);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkStringBuilder_Encode(objectPath,'url_rfc3986','utf-8');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
destinationSlashes := CkStringBuilder_Replace(objectPath,'%2F','/');
success := CkStringBuilder_Prepend(objectPath,'/');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'uploads','');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkRest_AddHeader(rest,'Content-Type','application/octet-stream');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
responseBody := CkRest__fullRequestNoBody(rest,'POST',CkStringBuilder__getAsString(objectPath));
if (CkRest_getLastMethodSuccess(rest) <> True) then
  begin
    Memo1.Lines.Add('Request did not complete; inspect diagnostics privately.');
    Exit;
  end;
if (CkRest_getResponseStatusCode(rest) <> 200) then
  begin
    Memo1.Lines.Add('S3 HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
    success := CkXml_LoadXml(xml,responseBody);
    CkStringBuilder_Clear(textCompare);
    CkStringBuilder_SetString(textCompare,CkXml__tag(xml));
    sameText8 := CkStringBuilder_ContentsEqual(textCompare,'Error',True);
    if ((success = True) and (sameText8 = True)) then
      begin
        Memo1.Lines.Add('S3 error code: ' + CkXml__getChildContent(xml,'Code'));
      end;
    //  Keep signed headers, credentials, URLs, and full diagnostics private.
    //  A timeout may leave a write's outcome uncertain. Check before retrying.
    Exit;
  end;
success := CkXml_LoadXml(xml,responseBody);
if (success <> True) then
  begin
    Memo1.Lines.Add('Expected well-formed XML.');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkXml__tag(xml));
sameText9 := CkStringBuilder_ContentsEqual(textCompare,'InitiateMultipartUploadResult',True);
if (sameText9 <> True) then
  begin
    Memo1.Lines.Add('Unexpected S3 response element; this is not a successful result.');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkXml__getChildContent(xml,'UploadId'));
sameText10 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkXml_HasChildWithTag(xml,'UploadId') <> True) or (sameText10 = True)) then
  begin
    Memo1.Lines.Add('Missing response field: UploadId');
    Exit;
  end;
uploadId := CkXml__getChildContent(xml,'UploadId');
state := CkJsonObject_Create();
success := CkJsonObject_UpdateString(state,'bucket',bucketName);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build saved state.');
    Exit;
  end;
success := CkJsonObject_UpdateString(state,'region',region);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build saved state.');
    Exit;
  end;
success := CkJsonObject_UpdateString(state,'key',destinationKey);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build saved state.');
    Exit;
  end;
success := CkJsonObject_UpdateString(state,'upload_id',uploadId);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build saved state.');
    Exit;
  end;
success := CkJsonObject_UpdateString(state,'source_key',objectKey);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build saved state.');
    Exit;
  end;
success := CkJsonObject_UpdateString(state,'source_etag',sourceEtag);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build saved state.');
    Exit;
  end;
success := CkJsonObject_UpdateString(state,'source_size',sourceSize);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build saved state.');
    Exit;
  end;
success := CkJsonObject_WriteFile(state,'s3-multipart.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Upload initiated but saving state failed; recover the upload ID or list unfinished uploads.');
    Exit;
  end;
success := CkRest_RemoveQueryParam(rest,'uploads');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkRest_RemoveHeader(rest,'Content-Type');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'uploadId',uploadId);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkRest_AddHeader(rest,'x-amz-copy-source',CkStringBuilder__getAsString(copySource));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkRest_AddHeader(rest,'x-amz-copy-source-if-match',sourceEtag);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
parts := CkXml_Create();
CkXml_putTag(parts,'CompleteMultipartUpload');
range := CkStringBuilder_Create();
ending := CkStringBuilder_Create();
number := CkStringBuilder_Create();
partNumber := 1;
while (partNumber <= numParts) do
  begin
    CkStringBuilder_Clear(range);
    CkStringBuilder_Clear(ending);
    CkStringBuilder_Clear(number);
    success := CkStringBuilder_Append(range,'bytes=');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not build text.');
        Exit;
      end;
    if (partNumber = 1) then
      begin
        success := CkStringBuilder_Append(range,'0');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not build text.');
            Exit;
          end;
      end
    else
      begin
        success := CkStringBuilder_AppendInt(range,partNumber - 1);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not prepare the request.');
            Exit;
          end;
        success := CkStringBuilder_Append(range,'000000000');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not build text.');
            Exit;
          end;
      end;
    success := CkStringBuilder_Append(range,'-');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not build text.');
        Exit;
      end;
    if (partNumber <= fullBillions) then
      begin
        if (partNumber > 1) then
          begin
            success := CkStringBuilder_AppendInt(ending,partNumber - 1);
            if (success <> True) then
              begin
                Memo1.Lines.Add('Could not prepare the request.');
                Exit;
              end;
          end;
        success := CkStringBuilder_Append(ending,'999999999');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not build text.');
            Exit;
          end;
      end
    else
      begin
        success := CkStringBuilder_AppendInt(ending,tailBytes - 1);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not prepare the request.');
            Exit;
          end;
        if (fullBillions > 0) then
          begin
            while (CkStringBuilder_getLength(ending) < 9) do
              begin
                success := CkStringBuilder_Prepend(ending,'0');
                if (success <> True) then
                  begin
                    Memo1.Lines.Add('Could not prepare the request.');
                    Exit;
                  end;
              end;

            success := CkStringBuilder_AppendInt(number,fullBillions);
            if (success <> True) then
              begin
                Memo1.Lines.Add('Could not prepare the request.');
                Exit;
              end;
            success := CkStringBuilder_Prepend(ending,CkStringBuilder__getAsString(number));
            if (success <> True) then
              begin
                Memo1.Lines.Add('Could not prepare the request.');
                Exit;
              end;
          end;
      end;
    success := CkStringBuilder_Append(range,CkStringBuilder__getAsString(ending));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not build text.');
        Exit;
      end;
    CkStringBuilder_Clear(number);
    success := CkStringBuilder_AppendInt(number,partNumber);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not prepare the request.');
        Exit;
      end;
    if (partNumber > 1) then
      begin
        success := CkRest_RemoveQueryParam(rest,'partNumber');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not prepare the request.');
            Exit;
          end;
        success := CkRest_RemoveHeader(rest,'x-amz-copy-source-range');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not prepare the request.');
            Exit;
          end;
      end;
    success := CkRest_AddQueryParam(rest,'partNumber',CkStringBuilder__getAsString(number));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not prepare the request.');
        Exit;
      end;
    success := CkRest_AddHeader(rest,'x-amz-copy-source-range',CkStringBuilder__getAsString(range));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not prepare the request.');
        Exit;
      end;
    responseBody := CkRest__fullRequestNoBody(rest,'PUT',CkStringBuilder__getAsString(objectPath));
    if (CkRest_getLastMethodSuccess(rest) <> True) then
      begin
        Memo1.Lines.Add('Request did not complete; inspect diagnostics privately.');
        Exit;
      end;
    if (CkRest_getResponseStatusCode(rest) <> 200) then
      begin
        Memo1.Lines.Add('S3 HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
        success := CkXml_LoadXml(xml,responseBody);
        CkStringBuilder_Clear(textCompare);
        CkStringBuilder_SetString(textCompare,CkXml__tag(xml));
        sameText11 := CkStringBuilder_ContentsEqual(textCompare,'Error',True);
        if ((success = True) and (sameText11 = True)) then
          begin
            Memo1.Lines.Add('S3 error code: ' + CkXml__getChildContent(xml,'Code'));
          end;
        //  Keep signed headers, credentials, URLs, and full diagnostics private.
        //  A timeout may leave a write's outcome uncertain. Check before retrying.
        Exit;
      end;
    success := CkXml_LoadXml(xml,responseBody);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Expected well-formed XML.');
        Exit;
      end;
    CkStringBuilder_Clear(textCompare);
    CkStringBuilder_SetString(textCompare,CkXml__tag(xml));
    sameText12 := CkStringBuilder_ContentsEqual(textCompare,'CopyPartResult',True);
    if (sameText12 <> True) then
      begin
        Memo1.Lines.Add('Unexpected S3 response element; this is not a successful result.');
        Exit;
      end;
    CkStringBuilder_Clear(textCompare);
    CkStringBuilder_SetString(textCompare,CkXml__getChildContent(xml,'ETag'));
    sameText13 := CkStringBuilder_ContentsEqual(textCompare,'',True);
    if ((CkXml_HasChildWithTag(xml,'ETag') <> True) or (sameText13 = True)) then
      begin
        Memo1.Lines.Add('Missing response field: ETag');
        Exit;
      end;
    CkXml_putI(parts,partNumber - 1);
    CkXml_UpdateChildContentInt(parts,'Part[i]|PartNumber',partNumber);
    CkXml_UpdateChildContent(parts,'Part[i]|ETag',CkXml__getChildContent(xml,'ETag'));
    Memo1.Lines.Add('Copied part: ' + IntToStr(partNumber));
    partNumber := partNumber + 1;
  end;

success := CkJsonObject_UpdateString(state,'completion_xml',CkXml__getXml(parts));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build saved state.');
    Exit;
  end;
success := CkJsonObject_WriteFile(state,'s3-multipart.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Parts copied but completion state could not be saved.');
    Exit;
  end;
success := CkRest_RemoveHeader(rest,'x-amz-copy-source');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkRest_RemoveHeader(rest,'x-amz-copy-source-if-match');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkRest_RemoveHeader(rest,'x-amz-copy-source-range');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkRest_RemoveQueryParam(rest,'partNumber');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkRest_AddHeader(rest,'Content-Type','application/xml');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
responseBody := CkRest__fullRequestString(rest,'POST',CkStringBuilder__getAsString(objectPath),CkXml__getXml(parts));
if (CkRest_getLastMethodSuccess(rest) <> True) then
  begin
    Memo1.Lines.Add('Request did not complete; inspect diagnostics privately.');
    Exit;
  end;
if (CkRest_getResponseStatusCode(rest) <> 200) then
  begin
    Memo1.Lines.Add('S3 HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
    success := CkXml_LoadXml(xml,responseBody);
    CkStringBuilder_Clear(textCompare);
    CkStringBuilder_SetString(textCompare,CkXml__tag(xml));
    sameText14 := CkStringBuilder_ContentsEqual(textCompare,'Error',True);
    if ((success = True) and (sameText14 = True)) then
      begin
        Memo1.Lines.Add('S3 error code: ' + CkXml__getChildContent(xml,'Code'));
      end;
    //  Keep signed headers, credentials, URLs, and full diagnostics private.
    //  A timeout may leave a write's outcome uncertain. Check before retrying.
    Exit;
  end;
success := CkXml_LoadXml(xml,responseBody);
if (success <> True) then
  begin
    Memo1.Lines.Add('Expected well-formed XML.');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkXml__tag(xml));
sameText15 := CkStringBuilder_ContentsEqual(textCompare,'CompleteMultipartUploadResult',True);
if (sameText15 <> True) then
  begin
    Memo1.Lines.Add('Unexpected S3 response element; this is not a successful result.');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkXml__getChildContent(xml,'ETag'));
sameText16 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkXml_HasChildWithTag(xml,'ETag') <> True) or (sameText16 = True)) then
  begin
    Memo1.Lines.Add('Missing response field: ETag');
    Exit;
  end;
Memo1.Lines.Add('Multipart copy completed; source was not deleted.');
//  Archive s3-multipart.json after confirming the destination.

CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkStringBuilder_Dispose(sizeText);
CkStringBuilder_Dispose(digits);
CkStringBuilder_Dispose(piece);
CkFileAccess_Dispose(files);
CkStringBuilder_Dispose(copySource);
    CkStringBuilder_Dispose(encodedVersion);
CkJsonObject_Dispose(state);
CkXml_Dispose(parts);
CkStringBuilder_Dispose(range);
CkStringBuilder_Dispose(ending);
CkStringBuilder_Dispose(number);