Sample code for 30+ languages & platforms
PureBasic Requires Chilkat v11.6.0+

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.

AWS reference

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkMime.pb"
IncludeFile "CkHttp.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkFileAccess.pb"

Procedure ChilkatExample()

    success.i = 0

    stringCompare.i = CkStringBuilder::ckCreate()
    If stringCompare.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  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.
    credentials.i = CkJsonObject::ckCreate()
    If credentials.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::setCkStrict(credentials, 1)
    success = CkJsonObject::ckLoadFile(credentials,"qa_data/aws/s3.json")
    If success <> 1
        Debug "Could not load private S3 credentials."
        CkStringBuilder::ckDispose(stringCompare)
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

    CkStringBuilder::ckSetString(stringCompare,CkJsonObject::ckStringOf(credentials,"access_key"))
    stringMatch1.i = CkStringBuilder::ckContentsEqual(stringCompare,"",1)
    If (CkJsonObject::ckJsonTypeOf(credentials,"access_key") <> 1) OR (stringMatch1 = 1)
        Debug "Missing or invalid access_key."
        CkStringBuilder::ckDispose(stringCompare)
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

    CkStringBuilder::ckSetString(stringCompare,CkJsonObject::ckStringOf(credentials,"secret_key"))
    stringMatch2.i = CkStringBuilder::ckContentsEqual(stringCompare,"",1)
    If (CkJsonObject::ckJsonTypeOf(credentials,"secret_key") <> 1) OR (stringMatch2 = 1)
        Debug "Missing or invalid secret_key."
        CkStringBuilder::ckDispose(stringCompare)
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

    http.i = CkHttp::ckCreate()
    If http.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkHttp::setCkAwsAccessKey(http, CkJsonObject::ckStringOf(credentials,"access_key"))
    CkHttp::setCkAwsSecretKey(http, CkJsonObject::ckStringOf(credentials,"secret_key"))
    If CkJsonObject::ckHasMember(credentials,"session_token") = 1
        CkStringBuilder::ckSetString(stringCompare,CkJsonObject::ckStringOf(credentials,"session_token"))
        stringMatch3.i = CkStringBuilder::ckContentsEqual(stringCompare,"",1)
        If (CkJsonObject::ckJsonTypeOf(credentials,"session_token") <> 1) OR (stringMatch3 = 1)
            Debug "session_token must be a nonempty string when supplied."
            CkStringBuilder::ckDispose(stringCompare)
            CkJsonObject::ckDispose(credentials)
            CkHttp::ckDispose(http)
            ProcedureReturn
        EndIf

        CkHttp::setCkAwsSessionToken(http, CkJsonObject::ckStringOf(credentials,"session_token"))
    EndIf

    ;  Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
    ;  Set the actual bucket region, not the caller's location.
    region.s = "us-west-2"
    CkHttp::setCkAwsRegion(http, region)
    endpoint.i = CkStringBuilder::ckCreate()
    If endpoint.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(endpoint,"s3.")
    CkStringBuilder::ckAppend(endpoint,region)
    CkStringBuilder::ckAppend(endpoint,".amazonaws.com")
    CkHttp::setCkAwsEndpoint(http, CkStringBuilder::ckGetAsString(endpoint))
    CkHttp::setCkRequireSslCertVerify(http, 1)
    CkHttp::setCkFollowRedirects(http, 0)
    ;  A region redirect is not success. Correct the endpoint and signing region.
    bucketName.s = "your-bucket-name"
    ;  A leading slash is part of a key. Do not add one to imitate a file path.
    objectName.s = "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.
    keyPath.i = CkStringBuilder::ckCreate()
    If keyPath.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(keyPath,CkHttp::ckUrlEncode(http,objectName))
    slashCount.i = CkStringBuilder::ckReplaceNoCase(keyPath,"%2f","/")
    encodedKey.s = CkStringBuilder::ckGetAsString(keyPath)
    files.i = CkFileAccess::ckCreate()
    If files.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    finalPath.s = "qa_output/seahorse.jpg"
    partialPath.s = "qa_output/seahorse.jpg.part"
    If (CkFileAccess::ckFileExists(files,finalPath) = 1) OR (CkFileAccess::ckFileExists(files,partialPath) = 1)
        Debug "Choose unused output paths before downloading."
        CkStringBuilder::ckDispose(stringCompare)
        CkJsonObject::ckDispose(credentials)
        CkHttp::ckDispose(http)
        CkStringBuilder::ckDispose(endpoint)
        CkStringBuilder::ckDispose(keyPath)
        CkFileAccess::ckDispose(files)
        ProcedureReturn
    EndIf

    success = CkHttp::ckS3_DownloadFile(http,bucketName,encodedKey,partialPath)
    If success <> 1
        Debug "Request failed (transport or S3 error). HTTP status: " + Str(CkHttp::ckLastStatus(http))
        ;  Inspect LastErrorText privately. Do not log credentials or signed URLs.
        CkStringBuilder::ckDispose(stringCompare)
        CkJsonObject::ckDispose(credentials)
        CkHttp::ckDispose(http)
        CkStringBuilder::ckDispose(endpoint)
        CkStringBuilder::ckDispose(keyPath)
        CkFileAccess::ckDispose(files)
        ProcedureReturn
    EndIf

    If CkHttp::ckLastStatus(http) <> 200
        Debug "Unexpected HTTP status: " + Str(CkHttp::ckLastStatus(http))
        CkStringBuilder::ckDispose(stringCompare)
        CkJsonObject::ckDispose(credentials)
        CkHttp::ckDispose(http)
        CkStringBuilder::ckDispose(endpoint)
        CkStringBuilder::ckDispose(keyPath)
        CkFileAccess::ckDispose(files)
        ProcedureReturn
    EndIf

    headers.i = CkMime::ckCreate()
    If headers.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkMime::ckLoadMime(headers,CkHttp::ckLastResponseHeader(http))
    If success <> 1
        Debug "Could not parse download headers; keep the .part file."
        CkStringBuilder::ckDispose(stringCompare)
        CkJsonObject::ckDispose(credentials)
        CkHttp::ckDispose(http)
        CkStringBuilder::ckDispose(endpoint)
        CkStringBuilder::ckDispose(keyPath)
        CkFileAccess::ckDispose(files)
        CkMime::ckDispose(headers)
        ProcedureReturn
    EndIf

    expectedSize.s = CkMime::ckGetHeaderField(headers,"Content-Length")
    CkStringBuilder::ckSetString(stringCompare,expectedSize)
    stringMatch4.i = CkStringBuilder::ckContentsEqual(stringCompare,"",1)
    If (CkMime::ckLastMethodSuccess(headers) <> 1) OR (stringMatch4 = 1)
        Debug "Missing Content-Length; keep the .part file."
        CkStringBuilder::ckDispose(stringCompare)
        CkJsonObject::ckDispose(credentials)
        CkHttp::ckDispose(http)
        CkStringBuilder::ckDispose(endpoint)
        CkStringBuilder::ckDispose(keyPath)
        CkFileAccess::ckDispose(files)
        CkMime::ckDispose(headers)
        ProcedureReturn
    EndIf

    actualSize.s = CkFileAccess::ckFileSizeStr(files,partialPath)
    CkStringBuilder::ckSetString(stringCompare,actualSize)
    stringMatch5.i = CkStringBuilder::ckContentsEqual(stringCompare,expectedSize,1)
    If (CkFileAccess::ckLastMethodSuccess(files) <> 1) OR (stringMatch5 <> 1)
        Debug "Downloaded byte count mismatch; keep the .part file."
        CkStringBuilder::ckDispose(stringCompare)
        CkJsonObject::ckDispose(credentials)
        CkHttp::ckDispose(http)
        CkStringBuilder::ckDispose(endpoint)
        CkStringBuilder::ckDispose(keyPath)
        CkFileAccess::ckDispose(files)
        CkMime::ckDispose(headers)
        ProcedureReturn
    EndIf

    success = CkFileAccess::ckFileRename(files,partialPath,finalPath)
    If success <> 1
        Debug "Downloaded file remains at the .part path; rename failed."
        CkStringBuilder::ckDispose(stringCompare)
        CkJsonObject::ckDispose(credentials)
        CkHttp::ckDispose(http)
        CkStringBuilder::ckDispose(endpoint)
        CkStringBuilder::ckDispose(keyPath)
        CkFileAccess::ckDispose(files)
        CkMime::ckDispose(headers)
        ProcedureReturn
    EndIf

    Debug "File download succeeded; byte count verified."


    CkStringBuilder::ckDispose(stringCompare)
    CkJsonObject::ckDispose(credentials)
    CkHttp::ckDispose(http)
    CkStringBuilder::ckDispose(endpoint)
    CkStringBuilder::ckDispose(keyPath)
    CkFileAccess::ckDispose(files)
    CkMime::ckDispose(headers)


    ProcedureReturn
EndProcedure