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 Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkSocketW.h>
#include <CkXmlW.h>
#include <CkFileAccessW.h>
#include <CkStreamW.h>
void ChilkatSample(void)
{
bool success = false;
// StringBuilder compares text by value in every generated language.
CkStringBuilderW textCompare;
// 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.
CkJsonObjectW credentials;
credentials.put_Strict(true);
success = credentials.LoadFile(L"qa_data/aws/s3.json");
if (success != true) {
wprintf(L"Could not load private AWS credentials.\n");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.stringOf(L"access_key"));
bool sameText1 = textCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"access_key") != 1) || (sameText1 == true)) {
wprintf(L"Missing or invalid access_key.\n");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.stringOf(L"secret_key"));
bool sameText2 = textCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"secret_key") != 1) || (sameText2 == true)) {
wprintf(L"Missing or invalid secret_key.\n");
return;
}
// General purpose bucket in the commercial AWS partition.
const wchar_t *region = L"us-west-2";
const wchar_t *bucketName = L"amzn-s3-demo-bucket";
CkStringBuilderW endpoint;
success = endpoint.Append(bucketName);
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = endpoint.Append(L".");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = endpoint.Append(L"s3.");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = endpoint.Append(region);
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = endpoint.Append(L".amazonaws.com");
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
CkAuthAwsW aws;
aws.put_AccessKey(credentials.stringOf(L"access_key"));
aws.put_SecretKey(credentials.stringOf(L"secret_key"));
aws.put_Region(region);
aws.put_ServiceName(L"s3");
aws.put_SignatureVersion(4);
CkRestW rest;
rest.put_ConnectTimeoutMs(20000);
rest.put_IdleTimeoutMs(60000);
success = rest.SetAuthAws(aws);
if (success != true) {
wprintf(L"Could not configure AWS signing.\n");
return;
}
// Temporary credentials require this token in every signed query.
// Keep request URLs private. Do not clear this parameter between requests.
if (credentials.HasMember(L"session_token") == true) {
if (credentials.JsonTypeOf(L"session_token") != 1) {
wprintf(L"session_token must be a string.\n");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.stringOf(L"session_token"));
bool sameText3 = textCompare.ContentsEqual(L"",true);
if (sameText3 != true) {
success = rest.AddQueryParam(L"X-Amz-Security-Token",credentials.stringOf(L"session_token"));
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
}
}
// Connect to the SAME hostname used for TLS verification and request signing.
CkSocketW connection;
connection.put_RequireSslCertVerify(true);
connection.put_MaxReadIdleMs(60000);
connection.put_MaxSendIdleMs(60000);
success = connection.Connect(endpoint.getAsString(),443,true,20000);
if (success != true) {
wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
return;
}
success = rest.UseConnection(connection,true);
if (success != true) {
wprintf(L"Could not attach the TLS connection.\n");
return;
}
CkXmlW xml;
xml.put_Strict(true);
// Supply an unencoded object key, not a URL. Preserve slashes in the key.
const wchar_t *objectKey = L"documents/example.txt";
CkStringBuilderW objectPath;
success = objectPath.Append(objectKey);
if (success != true) {
wprintf(L"Could not build text.\n");
return;
}
success = objectPath.Encode(L"url_rfc3986",L"utf-8");
if (success != true) {
wprintf(L"Could not encode the object key.\n");
return;
}
int restoredSlashes = objectPath.Replace(L"%2F",L"/");
success = objectPath.Prepend(L"/");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.SendReqNoBody(L"GET",objectPath.getAsString());
if (success != true) {
wprintf(L"Could not send download request.\n");
return;
}
int statusCode = rest.ReadResponseHeader();
if (statusCode < 0) {
wprintf(L"Could not read download headers.\n");
return;
}
if (statusCode != 200) {
wprintf(L"Download HTTP status: %d\n",statusCode);
const wchar_t *errorBody = rest.readRespBodyString();
if (rest.get_LastMethodSuccess() == true) {
success = xml.LoadXml(errorBody);
textCompare.Clear();
textCompare.SetString(xml.tag());
bool sameText4 = textCompare.ContentsEqual(L"Error",true);
if ((success == true) && (sameText4 == true)) {
wprintf(L"S3 error code: %s\n",xml.getChildContent(L"Code"));
}
}
return;
}
// Use a new staging filename. A failed transfer can leave a partial file.
CkFileAccessW files;
if ((files.FileExists(L"s3-download.part") == true) || (files.FileExists(L"s3-download.json") == true)) {
wprintf(L"A staging file or checkpoint already exists; choose new output paths.\n");
return;
}
// Save the original validator and length BEFORE reading the body so a failed
// download can be continued by the resume example.
const wchar_t *originalEtag = rest.responseHdrByName(L"ETag");
textCompare.Clear();
textCompare.SetString(originalEtag);
bool sameText5 = textCompare.ContentsEqual(L"",true);
if ((rest.get_LastMethodSuccess() != true) || (sameText5 == true)) {
wprintf(L"Missing object ETag.\n");
return;
}
const wchar_t *originalSize = rest.responseHdrByName(L"Content-Length");
textCompare.Clear();
textCompare.SetString(originalSize);
bool sameText6 = textCompare.ContentsEqual(L"",true);
if ((rest.get_LastMethodSuccess() != true) || (sameText6 == true)) {
wprintf(L"Missing object length.\n");
return;
}
CkJsonObjectW checkpoint;
success = checkpoint.UpdateString(L"bucket",bucketName);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = checkpoint.UpdateString(L"key",objectKey);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = checkpoint.UpdateString(L"region",region);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = checkpoint.UpdateString(L"etag",originalEtag);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = checkpoint.UpdateString(L"total_size",originalSize);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = checkpoint.WriteFile(L"s3-download.json");
if (success != true) {
wprintf(L"Could not save the resume checkpoint.\n");
return;
}
CkStreamW output;
output.put_SinkFile(L"s3-download.part");
output.put_SinkFileAppend(false);
success = rest.ReadRespBodyStream(output,true);
if (success != true) {
wprintf(L"Download incomplete; retain the partial file and checkpoint for the resume example.\n");
return;
}
const wchar_t *downloadedSize = files.fileSizeStr(L"s3-download.part");
textCompare.Clear();
textCompare.SetString(downloadedSize);
bool sameText7 = textCompare.ContentsEqual(originalSize,true);
if ((files.get_LastMethodSuccess() != true) || (sameText7 != true)) {
wprintf(L"Downloaded length does not match the original response.\n");
return;
}
wprintf(L"Download complete: s3-download.part\n");
}