Visual FoxPro 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"

Visual FoxPro Example

LOCAL loRest
LOCAL lnSuccess
LOCAL loAuthAws
LOCAL lnBTls
LOCAL lnPort
LOCAL lnBAutoReconnect
LOCAL loSbResponseBody
LOCAL lnRespStatusCode
LOCAL loXmlResponse
LOCAL lcCopyObjectResult_xmlns
LOCAL lcTagPath
LOCAL lcLastModified
LOCAL lcETag

loRest = CreateObject('Chilkat_9_5_0.Rest')

loAuthAws = CreateObject('Chilkat_9_5_0.AuthAws')
loAuthAws.AccessKey = "AWS_ACCESS_KEY"
loAuthAws.SecretKey = "AWS_SECRET_KEY"
loAuthAws.Region = "us-west-2"
loAuthAws.ServiceName = "s3"
loRest.SetAuthAws(loAuthAws)

*  URL: https://chilkat.ocean.s3.us-west-2.amazonaws.com/starfishCopy.jpg
lnBTls = 1
lnPort = 443
lnBAutoReconnect = 1
lnSuccess = loRest.Connect("chilkat.ocean.s3.us-west-2.amazonaws.com",lnPort,lnBTls,lnBAutoReconnect)
IF (lnSuccess <> 1) THEN
    ? "ConnectFailReason: " + STR(loRest.ConnectFailReason)
    ? loRest.LastErrorText
    RELEASE loRest
    RELEASE loAuthAws
    CANCEL
ENDIF

loRest.AddHeader("x-amz-copy-source","/chilkat.qa/starfish.jpg")

loSbResponseBody = CreateObject('Chilkat_9_5_0.StringBuilder')
lnSuccess = loRest.FullRequestNoBodySb("PUT","/starfishCopy.jpg",loSbResponseBody)
IF (lnSuccess <> 1) THEN
    ? loRest.LastErrorText
    RELEASE loRest
    RELEASE loAuthAws
    RELEASE loSbResponseBody
    CANCEL
ENDIF

lnRespStatusCode = loRest.ResponseStatusCode
IF (lnRespStatusCode >= 400) THEN
    ? "Response Status Code = " + STR(lnRespStatusCode)
    ? "Response Header:"
    ? loRest.ResponseHeader
    ? "Response Body:"
    ? loSbResponseBody.GetAsString()
    RELEASE loRest
    RELEASE loAuthAws
    RELEASE loSbResponseBody
    CANCEL
ENDIF

loXmlResponse = CreateObject('Chilkat_9_5_0.Xml')
loXmlResponse.LoadSb(loSbResponseBody,1)

*  See the Online Tool for Generating XML Parse Code

lcCopyObjectResult_xmlns = loXmlResponse.GetAttrValue("xmlns")
lcLastModified = loXmlResponse.GetChildContent("LastModified")
lcETag = loXmlResponse.GetChildContent("ETag")

RELEASE loRest
RELEASE loAuthAws
RELEASE loSbResponseBody
RELEASE loXmlResponse

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>