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

Amazon S3: Stream a File Upload with a Precomputed SHA-256

See more S3 - REST Examples

Upload one object with PutObject. Requires s3:PutObject; KMS-encrypted objects can need additional KMS permissions. An existing key is overwritten in an unversioned bucket or gets a new version when versioning is enabled. Successful PUT normally has an empty body. Do not label uncompressed data with Content-Encoding: gzip.

Precompute the SHA-256 in a separate file pass, then stream the unchanged file. This avoids buffering the whole file merely to calculate the signature. Clear PrecomputedSha256 before another request with different bytes. Use multipart upload for objects beyond the single PUT limit (5 GB), or to retry individual parts.

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.

AWS PutObject reference

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkAuthAws.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkSocket.pb"
IncludeFile "CkXml.pb"
IncludeFile "CkCrypt2.pb"
IncludeFile "CkStream.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkRest.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  StringBuilder compares text by value in every generated language.
    textCompare.i = CkStringBuilder::ckCreate()
    If textCompare.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = 0
    ;  Private configuration, not a file in public web content or source control.
    ;  Load current IAM credentials authorized for the S3 operation.
    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 AWS credentials."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

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

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

    ;  General purpose bucket in the commercial AWS partition.
    region.s = "us-west-2"
    bucketName.s = "amzn-s3-demo-bucket"
    endpoint.i = CkStringBuilder::ckCreate()
    If endpoint.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckAppend(endpoint,bucketName)
    If success <> 1
        Debug "Could not build text."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckAppend(endpoint,".")
    If success <> 1
        Debug "Could not build text."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckAppend(endpoint,"s3.")
    If success <> 1
        Debug "Could not build text."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckAppend(endpoint,region)
    If success <> 1
        Debug "Could not build text."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckAppend(endpoint,".amazonaws.com")
    If success <> 1
        Debug "Could not build text."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        ProcedureReturn
    EndIf

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

    CkAuthAws::setCkAccessKey(aws, CkJsonObject::ckStringOf(credentials,"access_key"))
    CkAuthAws::setCkSecretKey(aws, CkJsonObject::ckStringOf(credentials,"secret_key"))
    CkAuthAws::setCkRegion(aws, region)
    CkAuthAws::setCkServiceName(aws, "s3")
    CkAuthAws::setCkSignatureVersion(aws, 4)
    rest.i = CkRest::ckCreate()
    If rest.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkRest::setCkConnectTimeoutMs(rest, 20000)
    CkRest::setCkIdleTimeoutMs(rest, 60000)
    success = CkRest::ckSetAuthAws(rest,aws)
    If success <> 1
        Debug "Could not configure AWS signing."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        ProcedureReturn
    EndIf

    ;  Temporary credentials require this token in every signed query.
    ;  Keep request URLs private. Do not clear this parameter between requests.
    If CkJsonObject::ckHasMember(credentials,"session_token") = 1
        If CkJsonObject::ckJsonTypeOf(credentials,"session_token") <> 1
            Debug "session_token must be a string."
            CkStringBuilder::ckDispose(textCompare)
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            ProcedureReturn
        EndIf

        CkStringBuilder::ckClear(textCompare)
        CkStringBuilder::ckSetString(textCompare,CkJsonObject::ckStringOf(credentials,"session_token"))
        sameText3.i = CkStringBuilder::ckContentsEqual(textCompare,"",1)
        If sameText3 <> 1
            success = CkRest::ckAddQueryParam(rest,"X-Amz-Security-Token",CkJsonObject::ckStringOf(credentials,"session_token"))
            If success <> 1
                Debug "Could not prepare the request."
                CkStringBuilder::ckDispose(textCompare)
                CkJsonObject::ckDispose(credentials)
                CkStringBuilder::ckDispose(endpoint)
                CkAuthAws::ckDispose(aws)
                CkRest::ckDispose(rest)
                ProcedureReturn
            EndIf

        EndIf

    EndIf

    ;  Connect to the SAME hostname used for TLS verification and request signing.
    connection.i = CkSocket::ckCreate()
    If connection.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkSocket::setCkRequireSslCertVerify(connection, 1)
    CkSocket::setCkMaxReadIdleMs(connection, 60000)
    CkSocket::setCkMaxSendIdleMs(connection, 60000)
    success = CkSocket::ckConnect(connection,CkStringBuilder::ckGetAsString(endpoint),443,1,20000)
    If success <> 1
        Debug "TLS connection failed; inspect diagnostics privately."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        ProcedureReturn
    EndIf

    success = CkRest::ckUseConnection(rest,connection,1)
    If success <> 1
        Debug "Could not attach the TLS connection."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        ProcedureReturn
    EndIf

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

    CkXml::setCkStrict(xml, 1)
    ;  Supply an unencoded object key, not a URL. Preserve slashes in the key.
    objectKey.s = "documents/example.txt"
    objectPath.i = CkStringBuilder::ckCreate()
    If objectPath.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckAppend(objectPath,objectKey)
    If success <> 1
        Debug "Could not build text."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckEncode(objectPath,"url_rfc3986","utf-8")
    If success <> 1
        Debug "Could not encode the object key."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        ProcedureReturn
    EndIf

    restoredSlashes.i = CkStringBuilder::ckReplace(objectPath,"%2F","/")
    success = CkStringBuilder::ckPrepend(objectPath,"/")
    If success <> 1
        Debug "Could not prepare the request."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        ProcedureReturn
    EndIf

    success = CkRest::ckAddHeader(rest,"Content-Type","application/octet-stream")
    If success <> 1
        Debug "Could not prepare the request."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        ProcedureReturn
    EndIf

    ;  Keep the file unchanged from hashing until upload finishes.
    inputFile.s = "qa_data/files/example.bin"
    hash.i = CkCrypt2::ckCreate()
    If hash.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkCrypt2::setCkHashAlgorithm(hash, "sha256")
    CkCrypt2::setCkEncodingMode(hash, "hexlower")
    sha256.s = CkCrypt2::ckHashFileENC(hash,inputFile)
    If CkCrypt2::ckLastMethodSuccess(hash) <> 1
        Debug "Could not hash the file."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        CkCrypt2::ckDispose(hash)
        ProcedureReturn
    EndIf

    ;  Supply the payload hash for SigV4 without loading the whole file into memory.
    CkAuthAws::setCkPrecomputedSha256(aws, sha256)
    input.i = CkStream::ckCreate()
    If input.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStream::setCkSourceFile(input, inputFile)
    responseBody.s = CkRest::ckFullRequestStream(rest,"PUT",CkStringBuilder::ckGetAsString(objectPath),input)
    If CkRest::ckLastMethodSuccess(rest) <> 1
        Debug "Upload did not complete; inspect diagnostics privately."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        CkCrypt2::ckDispose(hash)
        CkStream::ckDispose(input)
        ProcedureReturn
    EndIf

    If CkRest::ckResponseStatusCode(rest) <> 200
        Debug "S3 HTTP status: " + Str(CkRest::ckResponseStatusCode(rest))
        success = CkXml::ckLoadXml(xml,responseBody)
        CkStringBuilder::ckClear(textCompare)
        CkStringBuilder::ckSetString(textCompare,CkXml::ckTag(xml))
        sameText4.i = CkStringBuilder::ckContentsEqual(textCompare,"Error",1)
        If (success = 1) AND (sameText4 = 1)
            Debug "S3 error code: " + CkXml::ckGetChildContent(xml,"Code")
        EndIf

        ;  Keep signed headers, credentials, URLs, and full diagnostics private.
        ;  A timeout may leave a write's outcome uncertain. Check before retrying.
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        CkCrypt2::ckDispose(hash)
        CkStream::ckDispose(input)
        ProcedureReturn
    EndIf

    ;  Clear this before reusing aws for a DIFFERENT request body.
    CkAuthAws::setCkPrecomputedSha256(aws, "")
    Debug "Object uploaded."
    Debug "ETag: " + CkRest::ckResponseHdrByName(rest,"ETag")
    ;  ETag is an opaque validator, not a universally valid MD5 checksum.


    CkStringBuilder::ckDispose(textCompare)
    CkJsonObject::ckDispose(credentials)
    CkStringBuilder::ckDispose(endpoint)
    CkAuthAws::ckDispose(aws)
    CkRest::ckDispose(rest)
    CkSocket::ckDispose(connection)
    CkXml::ckDispose(xml)
    CkStringBuilder::ckDispose(objectPath)
    CkCrypt2::ckDispose(hash)
    CkStream::ckDispose(input)


    ProcedureReturn
EndProcedure