S3: Download a File Safely
See more S3 - HTTP Examples
Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.
Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.
Downloads the exact key to an unused temporary path, requires HTTP 200, compares the local byte count with Content-Length, and renames only after success. Create the output directory first. Interrupted or failed downloads are not promoted to the final path. This is not a resumable download and does not independently verify an S3 checksum; ETag must not be assumed to be MD5.
Requires s3:GetObject, or s3:GetObjectVersion for a specified version, plus applicable KMS permissions. Archived S3 Glacier Flexible Retrieval or Deep Archive objects must be restored before reading; a restoration request does not immediately make them downloadable. Use the original key without adding a leading slash.
Chilkat B4X Downloads
Dim success As Boolean = False
Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
' This example requires the Chilkat API to have been previously unlocked.
' See Global Unlock Sample for sample code.
' Load private credentials; never put access keys or session tokens in source.
Dim credentials As ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/s3.json")
If success <> True Then
Log("Could not load private S3 credentials.")
Return
End If
stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = True) Then
Log("Missing or invalid access_key.")
Return
End If
stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = True) Then
Log("Missing or invalid secret_key.")
Return
End If
Dim http As ChilkatHttp
http.Initialize("http")
http.AwsAccessKey = credentials.StringOf("access_key")
http.AwsSecretKey = credentials.StringOf("secret_key")
If credentials.HasMember("session_token") = True Then
stringCompare.SetString(credentials.StringOf("session_token"))
Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = True) Then
Log("session_token must be a nonempty string when supplied.")
Return
End If
http.AwsSessionToken = credentials.StringOf("session_token")
End If
' Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
' Set the actual bucket region, not the caller's location.
Dim region As String = "us-west-2"
http.AwsRegion = region
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("s3.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
http.AwsEndpoint = endpoint.GetAsString
http.RequireSslCertVerify = True
http.FollowRedirects = False
' A region redirect is not success. Correct the endpoint and signing region.
Dim bucketName As String = "your-bucket-name"
' A leading slash is part of a key. Do not add one to imitate a file path.
Dim objectName As String = "images/seahorse.jpg"
' Start with the original key. Encode once and retain '/' path separators.
' This also protects a literal "%2F" from being interpreted as a slash.
Dim keyPath As ChilkatStringBuilder
keyPath.Initialize
keyPath.Append(http.UrlEncode(objectName))
Dim slashCount As Int = keyPath.ReplaceNoCase("%2f", "/")
Dim encodedKey As String = keyPath.GetAsString
Dim files As ChilkatFileAccess
files.Initialize
Dim finalPath As String = "qa_output/seahorse.jpg"
Dim partialPath As String = "qa_output/seahorse.jpg.part"
If (files.FileExists(finalPath) = True) Or (files.FileExists(partialPath) = True) Then
Log("Choose unused output paths before downloading.")
Return
End If
success = http.S3_DownloadFile(bucketName, encodedKey, partialPath)
If success <> True Then
Log("Request failed (transport or S3 error). HTTP status: " & http.LastStatus)
' Inspect LastErrorText privately. Do not log credentials or signed URLs.
Return
End If
If http.LastStatus <> 200 Then
Log("Unexpected HTTP status: " & http.LastStatus)
Return
End If
Dim headers As ChilkatMime
headers.Initialize
success = headers.LoadMime(http.LastResponseHeader)
If success <> True Then
Log("Could not parse download headers; keep the .part file.")
Return
End If
Dim expectedSize As String = headers.GetHeaderField("Content-Length")
stringCompare.SetString(expectedSize)
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("", True)
If (headers.LastMethodSuccess <> True) Or (stringMatch4 = True) Then
Log("Missing Content-Length; keep the .part file.")
Return
End If
Dim actualSize As String = files.FileSizeStr(partialPath)
stringCompare.SetString(actualSize)
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual(expectedSize, True)
If (files.LastMethodSuccess <> True) Or (stringMatch5 <> True) Then
Log("Downloaded byte count mismatch; keep the .part file.")
Return
End If
success = files.FileRename(partialPath, finalPath)
If success <> True Then
Log("Downloaded file remains at the .part path; rename failed.")
Return
End If
Log("File download succeeded; byte count verified.")