Rust
Rust
REST Stream Response to File (Streaming Download) (Amazon S3)
See more Amazon S3 (new) Examples
Demonstrates how to stream the response body directly to a file. (The example shows how to stream a JPG from the Amazon S3 service.)Chilkat Rust Downloads
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
let rest = chilkat::Rest::new();
// Connect to the Amazon AWS REST server.
let b_tls = true;
let port = 443;
let b_auto_reconnect = true;
let _ = rest.connect("s3.amazonaws.com", port, b_tls, b_auto_reconnect).is_ok();
// ----------------------------------------------------------------------------
// Important: For buckets created in regions outside us-east-1,
// there are three important changes that need to be made.
// See Working with S3 Buckets in Non-us-east-1 Regions for the details.
// ----------------------------------------------------------------------------
// Provide AWS credentials for the REST call.
let auth_aws = chilkat::AuthAws::new();
auth_aws.set_access_key("AWS_ACCESS_KEY");
auth_aws.set_secret_key("AWS_SECRET_KEY");
auth_aws.set_service_name("s3");
let _ = rest.set_auth_aws(&auth_aws).is_ok();
// Set the bucket name via the HOST header.
// In this case, the bucket name is "chilkat100".
rest.set_host("chilkat100.s3.amazonaws.com");
// Send the request to download the JPG.
if rest.send_req_no_body("GET", "/starfish.jpg").is_err() {
println!("{}", rest.last_error_text());
return;
}
// Read the response header.
let response_status_code = rest.read_response_header();
if response_status_code < 0 {
println!("{}", rest.last_error_text());
return;
}
println!("Response status code = {}", response_status_code);
// We expect a 200 response status if the JPG data is coming.
// Otherwise, we'll get a string response body with an error message(or no response body).
if response_status_code == 200 {
let body_stream = chilkat::Stream::new();
// The stream's sink will be a file.
body_stream.set_sink_file("qa_output/starfish.jpg");
// Read the response body to the stream. Given that we've
// set the stream's sink to a file, it will stream directly
// to the file.
if rest.read_resp_body_stream(&body_stream, true).is_err() {
println!("{}", rest.last_error_text());
return;
}
println!("Successfully received the JPG file.");
} else {
let err_response = rest.read_resp_body_string().unwrap_or_default();
if !rest.last_method_success() {
println!("{}", rest.last_error_text());
} else {
println!("{}", err_response);
}
}