Amazon S3: Stream an Object Download to a File
See more S3 - REST Examples
Download object bytes with GetObject after checking response headers. Requires s3:GetObject, and potentially kms:Decrypt. Archived objects may need restoration first. HTTP 403 can mean insufficient permission, including a missing object when ListBucket is not allowed; it does not prove existence.
The output is streamed to a new staging file. Publish or rename it only after successful completion. Do not treat a partially written file as complete.
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.
Chilkat DataFlex Downloads
Use ChilkatAx-win32.pkg
Procedure Test
Boolean iSuccess
Handle hoTextCompare
Handle hoCredentials
Boolean iSameText1
Boolean iSameText2
String sRegion
String sBucketName
Handle hoEndpoint
Variant vAws
Handle hoAws
Handle hoRest
Boolean iSameText3
Variant vConnection
Handle hoConnection
Handle hoXml
String sObjectKey
Handle hoObjectPath
Integer iRestoredSlashes
Integer iStatusCode
String sErrorBody
Boolean iSameText4
Handle hoFiles
String sOriginalEtag
Boolean iSameText5
String sOriginalSize
Boolean iSameText6
Handle hoCheckpoint
Variant vOutput
Handle hoOutput
String sDownloadedSize
Boolean iSameText7
String sTemp1
Integer iTemp1
Boolean bTemp1
Boolean bTemp2
Move False To iSuccess
// StringBuilder compares text by value in every generated language.
Get Create (RefClass(cComChilkatStringBuilder)) To hoTextCompare
If (Not(IsComObjectCreated(hoTextCompare))) Begin
Send CreateComObject of hoTextCompare
End
// Assumes Chilkat is unlocked. See Global Unlock Sample.
Move False To iSuccess
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the S3 operation.
Get Create (RefClass(cComChilkatJsonObject)) To hoCredentials
If (Not(IsComObjectCreated(hoCredentials))) Begin
Send CreateComObject of hoCredentials
End
Set ComStrict Of hoCredentials To True
Get ComLoadFile Of hoCredentials "qa_data/aws/s3.json" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not load private AWS credentials."
Procedure_Return
End
Send ComClear To hoTextCompare
Get ComStringOf Of hoCredentials "access_key" To sTemp1
Get ComSetString Of hoTextCompare sTemp1 To iSuccess
Get ComContentsEqual Of hoTextCompare "" True To iSameText1
Get ComJsonTypeOf Of hoCredentials "access_key" To iTemp1
If ((iTemp1 <> 1) Or (iSameText1 = True)) Begin
Showln "Missing or invalid access_key."
Procedure_Return
End
Send ComClear To hoTextCompare
Get ComStringOf Of hoCredentials "secret_key" To sTemp1
Get ComSetString Of hoTextCompare sTemp1 To iSuccess
Get ComContentsEqual Of hoTextCompare "" True To iSameText2
Get ComJsonTypeOf Of hoCredentials "secret_key" To iTemp1
If ((iTemp1 <> 1) Or (iSameText2 = True)) Begin
Showln "Missing or invalid secret_key."
Procedure_Return
End
// General purpose bucket in the commercial AWS partition.
Move "us-west-2" To sRegion
Move "amzn-s3-demo-bucket" To sBucketName
Get Create (RefClass(cComChilkatStringBuilder)) To hoEndpoint
If (Not(IsComObjectCreated(hoEndpoint))) Begin
Send CreateComObject of hoEndpoint
End
Get ComAppend Of hoEndpoint sBucketName To iSuccess
If (iSuccess <> True) Begin
Showln "Could not build text."
Procedure_Return
End
Get ComAppend Of hoEndpoint "." To iSuccess
If (iSuccess <> True) Begin
Showln "Could not build text."
Procedure_Return
End
Get ComAppend Of hoEndpoint "s3." To iSuccess
If (iSuccess <> True) Begin
Showln "Could not build text."
Procedure_Return
End
Get ComAppend Of hoEndpoint sRegion To iSuccess
If (iSuccess <> True) Begin
Showln "Could not build text."
Procedure_Return
End
Get ComAppend Of hoEndpoint ".amazonaws.com" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not build text."
Procedure_Return
End
Get Create (RefClass(cComChilkatAuthAws)) To hoAws
If (Not(IsComObjectCreated(hoAws))) Begin
Send CreateComObject of hoAws
End
Get ComStringOf Of hoCredentials "access_key" To sTemp1
Set ComAccessKey Of hoAws To sTemp1
Get ComStringOf Of hoCredentials "secret_key" To sTemp1
Set ComSecretKey Of hoAws To sTemp1
Set ComRegion Of hoAws To sRegion
Set ComServiceName Of hoAws To "s3"
Set ComSignatureVersion Of hoAws To 4
Get Create (RefClass(cComChilkatRest)) To hoRest
If (Not(IsComObjectCreated(hoRest))) Begin
Send CreateComObject of hoRest
End
Set ComConnectTimeoutMs Of hoRest To 20000
Set ComIdleTimeoutMs Of hoRest To 60000
Get pvComObject of hoAws to vAws
Get ComSetAuthAws Of hoRest vAws To iSuccess
If (iSuccess <> True) Begin
Showln "Could not configure AWS signing."
Procedure_Return
End
// Temporary credentials require this token in every signed query.
// Keep request URLs private. Do not clear this parameter between requests.
Get ComHasMember Of hoCredentials "session_token" To bTemp1
If (bTemp1 = True) Begin
Get ComJsonTypeOf Of hoCredentials "session_token" To iTemp1
If (iTemp1 <> 1) Begin
Showln "session_token must be a string."
Procedure_Return
End
Send ComClear To hoTextCompare
Get ComStringOf Of hoCredentials "session_token" To sTemp1
Get ComSetString Of hoTextCompare sTemp1 To iSuccess
Get ComContentsEqual Of hoTextCompare "" True To iSameText3
If (iSameText3 <> True) Begin
Get ComStringOf Of hoCredentials "session_token" To sTemp1
Get ComAddQueryParam Of hoRest "X-Amz-Security-Token" sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Could not prepare the request."
Procedure_Return
End
End
End
// Connect to the SAME hostname used for TLS verification and request signing.
Get Create (RefClass(cComChilkatSocket)) To hoConnection
If (Not(IsComObjectCreated(hoConnection))) Begin
Send CreateComObject of hoConnection
End
Set ComRequireSslCertVerify Of hoConnection To True
Set ComMaxReadIdleMs Of hoConnection To 60000
Set ComMaxSendIdleMs Of hoConnection To 60000
Get ComGetAsString Of hoEndpoint To sTemp1
Get ComConnect Of hoConnection sTemp1 443 True 20000 To iSuccess
If (iSuccess <> True) Begin
Showln "TLS connection failed; inspect diagnostics privately."
Procedure_Return
End
Get pvComObject of hoConnection to vConnection
Get ComUseConnection Of hoRest vConnection True To iSuccess
If (iSuccess <> True) Begin
Showln "Could not attach the TLS connection."
Procedure_Return
End
Get Create (RefClass(cComChilkatXml)) To hoXml
If (Not(IsComObjectCreated(hoXml))) Begin
Send CreateComObject of hoXml
End
Set ComStrict Of hoXml To True
// Supply an unencoded object key, not a URL. Preserve slashes in the key.
Move "documents/example.txt" To sObjectKey
Get Create (RefClass(cComChilkatStringBuilder)) To hoObjectPath
If (Not(IsComObjectCreated(hoObjectPath))) Begin
Send CreateComObject of hoObjectPath
End
Get ComAppend Of hoObjectPath sObjectKey To iSuccess
If (iSuccess <> True) Begin
Showln "Could not build text."
Procedure_Return
End
Get ComEncode Of hoObjectPath "url_rfc3986" "utf-8" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not encode the object key."
Procedure_Return
End
Get ComReplace Of hoObjectPath "%2F" "/" To iRestoredSlashes
Get ComPrepend Of hoObjectPath "/" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not prepare the request."
Procedure_Return
End
Get ComGetAsString Of hoObjectPath To sTemp1
Get ComSendReqNoBody Of hoRest "GET" sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Could not send download request."
Procedure_Return
End
Get ComReadResponseHeader Of hoRest To iStatusCode
If (iStatusCode < 0) Begin
Showln "Could not read download headers."
Procedure_Return
End
If (iStatusCode <> 200) Begin
Showln "Download HTTP status: " iStatusCode
Get ComReadRespBodyString Of hoRest To sErrorBody
Get ComLastMethodSuccess Of hoRest To bTemp1
If (bTemp1 = True) Begin
Get ComLoadXml Of hoXml sErrorBody To iSuccess
Send ComClear To hoTextCompare
Get ComTag Of hoXml To sTemp1
Get ComSetString Of hoTextCompare sTemp1 To iSuccess
Get ComContentsEqual Of hoTextCompare "Error" True To iSameText4
If ((iSuccess = True) And (iSameText4 = True)) Begin
Get ComGetChildContent Of hoXml "Code" To sTemp1
Showln "S3 error code: " sTemp1
End
End
Procedure_Return
End
// Use a new staging filename. A failed transfer can leave a partial file.
Get Create (RefClass(cComCkFileAccess)) To hoFiles
If (Not(IsComObjectCreated(hoFiles))) Begin
Send CreateComObject of hoFiles
End
Get ComFileExists Of hoFiles "s3-download.part" To bTemp1
Get ComFileExists Of hoFiles "s3-download.json" To bTemp2
If ((bTemp1 = True) Or (bTemp2 = True)) Begin
Showln "A staging file or checkpoint already exists; choose new output paths."
Procedure_Return
End
// Save the original validator and length BEFORE reading the body so a failed
// download can be continued by the resume example.
Get ComResponseHdrByName Of hoRest "ETag" To sOriginalEtag
Send ComClear To hoTextCompare
Get ComSetString Of hoTextCompare sOriginalEtag To iSuccess
Get ComContentsEqual Of hoTextCompare "" True To iSameText5
Get ComLastMethodSuccess Of hoRest To bTemp1
If ((bTemp1 <> True) Or (iSameText5 = True)) Begin
Showln "Missing object ETag."
Procedure_Return
End
Get ComResponseHdrByName Of hoRest "Content-Length" To sOriginalSize
Send ComClear To hoTextCompare
Get ComSetString Of hoTextCompare sOriginalSize To iSuccess
Get ComContentsEqual Of hoTextCompare "" True To iSameText6
Get ComLastMethodSuccess Of hoRest To bTemp1
If ((bTemp1 <> True) Or (iSameText6 = True)) Begin
Showln "Missing object length."
Procedure_Return
End
Get Create (RefClass(cComChilkatJsonObject)) To hoCheckpoint
If (Not(IsComObjectCreated(hoCheckpoint))) Begin
Send CreateComObject of hoCheckpoint
End
Get ComUpdateString Of hoCheckpoint "bucket" sBucketName To iSuccess
If (iSuccess <> True) Begin
Showln "Could not prepare the request."
Procedure_Return
End
Get ComUpdateString Of hoCheckpoint "key" sObjectKey To iSuccess
If (iSuccess <> True) Begin
Showln "Could not prepare the request."
Procedure_Return
End
Get ComUpdateString Of hoCheckpoint "region" sRegion To iSuccess
If (iSuccess <> True) Begin
Showln "Could not prepare the request."
Procedure_Return
End
Get ComUpdateString Of hoCheckpoint "etag" sOriginalEtag To iSuccess
If (iSuccess <> True) Begin
Showln "Could not prepare the request."
Procedure_Return
End
Get ComUpdateString Of hoCheckpoint "total_size" sOriginalSize To iSuccess
If (iSuccess <> True) Begin
Showln "Could not prepare the request."
Procedure_Return
End
Get ComWriteFile Of hoCheckpoint "s3-download.json" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not save the resume checkpoint."
Procedure_Return
End
Get Create (RefClass(cComChilkatStream)) To hoOutput
If (Not(IsComObjectCreated(hoOutput))) Begin
Send CreateComObject of hoOutput
End
Set ComSinkFile Of hoOutput To "s3-download.part"
Set ComSinkFileAppend Of hoOutput To False
Get pvComObject of hoOutput to vOutput
Get ComReadRespBodyStream Of hoRest vOutput True To iSuccess
If (iSuccess <> True) Begin
Showln "Download incomplete; retain the partial file and checkpoint for the resume example."
Procedure_Return
End
Get ComFileSizeStr Of hoFiles "s3-download.part" To sDownloadedSize
Send ComClear To hoTextCompare
Get ComSetString Of hoTextCompare sDownloadedSize To iSuccess
Get ComContentsEqual Of hoTextCompare sOriginalSize True To iSameText7
Get ComLastMethodSuccess Of hoFiles To bTemp1
If ((bTemp1 <> True) Or (iSameText7 <> True)) Begin
Showln "Downloaded length does not match the original response."
Procedure_Return
End
Showln "Download complete: s3-download.part"
End_Procedure