Delphi ActiveX AWS S3: Copy S3 File to a Different Bucket

Back to Index

Demonstrates how to copy an S3 file from one bucket to another. The file can also be renamed if desired. (The file already exists in S3 in one bucket, and is copied without downloading/uploading to another S3 bucket.) This example copies from /chilkat.qa/starfish.jpg to /chilkat.ocean/starfishCopy.jpg

Documentation: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectCOPY.html

CURL Command

curl -X PUT https://chilkat.ocean.s3.us-west-2.amazonaws.com/starfishCopy.jpg \
    -H "x-amz-copy-source: /chilkat.qa/starfish.jpg"

Delphi ActiveX Example

var
rest: TChilkatRest;
success: Integer;
authAws: TChilkatAuthAws;
bTls: Integer;
port: Integer;
bAutoReconnect: Integer;
sbResponseBody: TChilkatStringBuilder;
respStatusCode: Integer;
xmlResponse: TChilkatXml;
CopyObjectResult_xmlns: WideString;
tagPath: WideString;
LastModified: WideString;
ETag: WideString;

begin
rest := TChilkatRest.Create(Self);

authAws := TChilkatAuthAws.Create(Self);
authAws.AccessKey := 'AWS_ACCESS_KEY';
authAws.SecretKey := 'AWS_SECRET_KEY';
authAws.Region := 'us-west-2';
authAws.ServiceName := 's3';
rest.SetAuthAws(authAws.ControlInterface);

//  URL: https://chilkat.ocean.s3.us-west-2.amazonaws.com/starfishCopy.jpg
bTls := 1;
port := 443;
bAutoReconnect := 1;
success := rest.Connect('chilkat.ocean.s3.us-west-2.amazonaws.com',port,bTls,bAutoReconnect);
if (success <> 1) then
  begin
    Memo1.Lines.Add('ConnectFailReason: ' + IntToStr(rest.ConnectFailReason));
    Memo1.Lines.Add(rest.LastErrorText);
    Exit;
  end;

rest.AddHeader('x-amz-copy-source','/chilkat.qa/starfish.jpg');

sbResponseBody := TChilkatStringBuilder.Create(Self);
success := rest.FullRequestNoBodySb('PUT','/starfishCopy.jpg',sbResponseBody.ControlInterface);
if (success <> 1) then
  begin
    Memo1.Lines.Add(rest.LastErrorText);
    Exit;
  end;
respStatusCode := rest.ResponseStatusCode;
if (respStatusCode >= 400) then
  begin
    Memo1.Lines.Add('Response Status Code = ' + IntToStr(respStatusCode));
    Memo1.Lines.Add('Response Header:');
    Memo1.Lines.Add(rest.ResponseHeader);
    Memo1.Lines.Add('Response Body:');
    Memo1.Lines.Add(sbResponseBody.GetAsString());
    Exit;
  end;

xmlResponse := TChilkatXml.Create(Self);
xmlResponse.LoadSb(sbResponseBody.ControlInterface,1);

//  See the Online Tool for Generating XML Parse Code

CopyObjectResult_xmlns := xmlResponse.GetAttrValue('xmlns');
LastModified := xmlResponse.GetChildContent('LastModified');
ETag := xmlResponse.GetChildContent('ETag');

Sample XML Response Body

<?xml version="1.0" encoding="UTF-8"?>
<CopyObjectResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <LastModified>2018-12-18T15:53:32.000Z</LastModified>
    <ETag>"2e9c59dbf2662367dc97dfdda85da048"</ETag>
</CopyObjectResult>