Tcl 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"

Tcl Example


load ./chilkat.dll

set rest [new_CkRest]

set authAws [new_CkAuthAws]

CkAuthAws_put_AccessKey $authAws "AWS_ACCESS_KEY"
CkAuthAws_put_SecretKey $authAws "AWS_SECRET_KEY"
CkAuthAws_put_Region $authAws "us-west-2"
CkAuthAws_put_ServiceName $authAws "s3"
CkRest_SetAuthAws $rest $authAws

#  URL: https://chilkat.ocean.s3.us-west-2.amazonaws.com/starfishCopy.jpg
set bTls 1
set port 443
set bAutoReconnect 1
set success [CkRest_Connect $rest "chilkat.ocean.s3.us-west-2.amazonaws.com" $port $bTls $bAutoReconnect]
if {[expr $success != 1]} then {
    puts "ConnectFailReason: [CkRest_get_ConnectFailReason $rest]"
    puts [CkRest_lastErrorText $rest]
    delete_CkRest $rest
    delete_CkAuthAws $authAws
    exit
}

CkRest_AddHeader $rest "x-amz-copy-source" "/chilkat.qa/starfish.jpg"

set sbResponseBody [new_CkStringBuilder]

set success [CkRest_FullRequestNoBodySb $rest "PUT" "/starfishCopy.jpg" $sbResponseBody]
if {[expr $success != 1]} then {
    puts [CkRest_lastErrorText $rest]
    delete_CkRest $rest
    delete_CkAuthAws $authAws
    delete_CkStringBuilder $sbResponseBody
    exit
}

set respStatusCode [CkRest_get_ResponseStatusCode $rest]
if {[expr $respStatusCode >= 400]} then {
    puts "Response Status Code = $respStatusCode"
    puts "Response Header:"
    puts [CkRest_responseHeader $rest]
    puts "Response Body:"
    puts [CkStringBuilder_getAsString $sbResponseBody]
    delete_CkRest $rest
    delete_CkAuthAws $authAws
    delete_CkStringBuilder $sbResponseBody
    exit
}

set xmlResponse [new_CkXml]

CkXml_LoadSb $xmlResponse $sbResponseBody 1

#  See the Online Tool for Generating XML Parse Code

set CopyObjectResult_xmlns [CkXml_getAttrValue $xmlResponse "xmlns"]
set LastModified [CkXml_getChildContent $xmlResponse "LastModified"]
set ETag [CkXml_getChildContent $xmlResponse "ETag"]

delete_CkRest $rest
delete_CkAuthAws $authAws
delete_CkStringBuilder $sbResponseBody
delete_CkXml $xmlResponse

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>