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 C Downloads
#include <C_CkStringBuilder.h>
#include <C_CkJsonObject.h>
#include <C_CkAuthAws.h>
#include <C_CkRest.h>
#include <C_CkSocket.h>
#include <C_CkXml.h>
#include <C_CkFileAccess.h>
#include <C_CkStream.h>
void ChilkatSample(void)
{
BOOL success;
HCkStringBuilder textCompare;
HCkJsonObject credentials;
BOOL sameText1;
BOOL sameText2;
const char *region;
const char *bucketName;
HCkStringBuilder endpoint;
HCkAuthAws aws;
HCkRest rest;
BOOL sameText3;
HCkSocket connection;
HCkXml xml;
const char *objectKey;
HCkStringBuilder objectPath;
int restoredSlashes;
int statusCode;
const char *errorBody;
BOOL sameText4;
HCkFileAccess files;
const char *originalEtag;
BOOL sameText5;
const char *originalSize;
BOOL sameText6;
HCkJsonObject checkpoint;
HCkStream output;
const char *downloadedSize;
BOOL sameText7;
success = FALSE;
// StringBuilder compares text by value in every generated language.
textCompare = CkStringBuilder_Create();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = FALSE;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the S3 operation.
credentials = CkJsonObject_Create();
CkJsonObject_putStrict(credentials,TRUE);
success = CkJsonObject_LoadFile(credentials,"qa_data/aws/s3.json");
if (success != TRUE) {
printf("Could not load private AWS credentials.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
return;
}
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkJsonObject_stringOf(credentials,"access_key"));
sameText1 = CkStringBuilder_ContentsEqual(textCompare,"",TRUE);
if ((CkJsonObject_JsonTypeOf(credentials,"access_key") != 1) || (sameText1 == TRUE)) {
printf("Missing or invalid access_key.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
return;
}
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkJsonObject_stringOf(credentials,"secret_key"));
sameText2 = CkStringBuilder_ContentsEqual(textCompare,"",TRUE);
if ((CkJsonObject_JsonTypeOf(credentials,"secret_key") != 1) || (sameText2 == TRUE)) {
printf("Missing or invalid secret_key.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
return;
}
// General purpose bucket in the commercial AWS partition.
region = "us-west-2";
bucketName = "amzn-s3-demo-bucket";
endpoint = CkStringBuilder_Create();
success = CkStringBuilder_Append(endpoint,bucketName);
if (success != TRUE) {
printf("Could not build text.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
return;
}
success = CkStringBuilder_Append(endpoint,".");
if (success != TRUE) {
printf("Could not build text.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
return;
}
success = CkStringBuilder_Append(endpoint,"s3.");
if (success != TRUE) {
printf("Could not build text.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
return;
}
success = CkStringBuilder_Append(endpoint,region);
if (success != TRUE) {
printf("Could not build text.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
return;
}
success = CkStringBuilder_Append(endpoint,".amazonaws.com");
if (success != TRUE) {
printf("Could not build text.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
return;
}
aws = CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject_stringOf(credentials,"access_key"));
CkAuthAws_putSecretKey(aws,CkJsonObject_stringOf(credentials,"secret_key"));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,"s3");
CkAuthAws_putSignatureVersion(aws,4);
rest = CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
success = CkRest_SetAuthAws(rest,aws);
if (success != TRUE) {
printf("Could not configure AWS signing.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
return;
}
// Temporary credentials require this token in every signed query.
// Keep request URLs private. Do not clear this parameter between requests.
if (CkJsonObject_HasMember(credentials,"session_token") == TRUE) {
if (CkJsonObject_JsonTypeOf(credentials,"session_token") != 1) {
printf("session_token must be a string.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
return;
}
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkJsonObject_stringOf(credentials,"session_token"));
sameText3 = CkStringBuilder_ContentsEqual(textCompare,"",TRUE);
if (sameText3 != TRUE) {
success = CkRest_AddQueryParam(rest,"X-Amz-Security-Token",CkJsonObject_stringOf(credentials,"session_token"));
if (success != TRUE) {
printf("Could not prepare the request.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
return;
}
}
}
// Connect to the SAME hostname used for TLS verification and request signing.
connection = CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,TRUE);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success = CkSocket_Connect(connection,CkStringBuilder_getAsString(endpoint),443,TRUE,20000);
if (success != TRUE) {
printf("TLS connection failed; inspect diagnostics privately.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
return;
}
success = CkRest_UseConnection(rest,connection,TRUE);
if (success != TRUE) {
printf("Could not attach the TLS connection.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
return;
}
xml = CkXml_Create();
CkXml_putStrict(xml,TRUE);
// Supply an unencoded object key, not a URL. Preserve slashes in the key.
objectKey = "documents/example.txt";
objectPath = CkStringBuilder_Create();
success = CkStringBuilder_Append(objectPath,objectKey);
if (success != TRUE) {
printf("Could not build text.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
return;
}
success = CkStringBuilder_Encode(objectPath,"url_rfc3986","utf-8");
if (success != TRUE) {
printf("Could not encode the object key.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
return;
}
restoredSlashes = CkStringBuilder_Replace(objectPath,"%2F","/");
success = CkStringBuilder_Prepend(objectPath,"/");
if (success != TRUE) {
printf("Could not prepare the request.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
return;
}
success = CkRest_SendReqNoBody(rest,"GET",CkStringBuilder_getAsString(objectPath));
if (success != TRUE) {
printf("Could not send download request.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
return;
}
statusCode = CkRest_ReadResponseHeader(rest);
if (statusCode < 0) {
printf("Could not read download headers.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
return;
}
if (statusCode != 200) {
printf("Download HTTP status: %d\n",statusCode);
errorBody = CkRest_readRespBodyString(rest);
if (CkRest_getLastMethodSuccess(rest) == TRUE) {
success = CkXml_LoadXml(xml,errorBody);
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkXml_tag(xml));
sameText4 = CkStringBuilder_ContentsEqual(textCompare,"Error",TRUE);
if ((success == TRUE) && (sameText4 == TRUE)) {
printf("S3 error code: %s\n",CkXml_getChildContent(xml,"Code"));
}
}
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
return;
}
// Use a new staging filename. A failed transfer can leave a partial file.
files = CkFileAccess_Create();
if ((CkFileAccess_FileExists(files,"s3-download.part") == TRUE) || (CkFileAccess_FileExists(files,"s3-download.json") == TRUE)) {
printf("A staging file or checkpoint already exists; choose new output paths.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
return;
}
// Save the original validator and length BEFORE reading the body so a failed
// download can be continued by the resume example.
originalEtag = CkRest_responseHdrByName(rest,"ETag");
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,originalEtag);
sameText5 = CkStringBuilder_ContentsEqual(textCompare,"",TRUE);
if ((CkRest_getLastMethodSuccess(rest) != TRUE) || (sameText5 == TRUE)) {
printf("Missing object ETag.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
return;
}
originalSize = CkRest_responseHdrByName(rest,"Content-Length");
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,originalSize);
sameText6 = CkStringBuilder_ContentsEqual(textCompare,"",TRUE);
if ((CkRest_getLastMethodSuccess(rest) != TRUE) || (sameText6 == TRUE)) {
printf("Missing object length.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
return;
}
checkpoint = CkJsonObject_Create();
success = CkJsonObject_UpdateString(checkpoint,"bucket",bucketName);
if (success != TRUE) {
printf("Could not prepare the request.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(checkpoint);
return;
}
success = CkJsonObject_UpdateString(checkpoint,"key",objectKey);
if (success != TRUE) {
printf("Could not prepare the request.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(checkpoint);
return;
}
success = CkJsonObject_UpdateString(checkpoint,"region",region);
if (success != TRUE) {
printf("Could not prepare the request.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(checkpoint);
return;
}
success = CkJsonObject_UpdateString(checkpoint,"etag",originalEtag);
if (success != TRUE) {
printf("Could not prepare the request.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(checkpoint);
return;
}
success = CkJsonObject_UpdateString(checkpoint,"total_size",originalSize);
if (success != TRUE) {
printf("Could not prepare the request.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(checkpoint);
return;
}
success = CkJsonObject_WriteFile(checkpoint,"s3-download.json");
if (success != TRUE) {
printf("Could not save the resume checkpoint.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(checkpoint);
return;
}
output = CkStream_Create();
CkStream_putSinkFile(output,"s3-download.part");
CkStream_putSinkFileAppend(output,FALSE);
success = CkRest_ReadRespBodyStream(rest,output,TRUE);
if (success != TRUE) {
printf("Download incomplete; retain the partial file and checkpoint for the resume example.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(checkpoint);
CkStream_Dispose(output);
return;
}
downloadedSize = CkFileAccess_fileSizeStr(files,"s3-download.part");
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,downloadedSize);
sameText7 = CkStringBuilder_ContentsEqual(textCompare,originalSize,TRUE);
if ((CkFileAccess_getLastMethodSuccess(files) != TRUE) || (sameText7 != TRUE)) {
printf("Downloaded length does not match the original response.\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(checkpoint);
CkStream_Dispose(output);
return;
}
printf("Download complete: s3-download.part\n");
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(checkpoint);
CkStream_Dispose(output);
}