Sample code for 30+ languages & platforms
Rust

Download Object from Google Cloud Storage

See more Google Cloud Storage Examples

Demonstrates how to download an object from Google Cloud Storage to a file.

Chilkat Rust Downloads

Rust

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

// This example uses a previously obtained access token having permission for the 
// scope "https://www.googleapis.com/auth/cloud-platform"

// In this example, Get Google Cloud Storage OAuth2 Access Token, 
// the service account access token was saved to a text file.  This example fetches the access token from the file..
let sb_token = chilkat::StringBuilder::new();
let _ = sb_token.load_file("qa_data/tokens/googleCloudStorageAccessToken.txt", "utf-8");

// Send a GET equivalent to this curl command.

// curl -X GET \
//     -H "Authorization: Bearer [OAUTH2_TOKEN]" \
//     -o "[SAVE_TO_LOCATION]" \
//     "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[OBJECT_NAME]?alt=media"

let http = chilkat::Http::new();

http.set_auth_token(&sb_token.get_as_string().unwrap_or_default());

// Construct a URL to download an object named "starfish.jpg" from the "chilkat-ocean" bucket.
let _ = http.set_url_var("bucket_name", "chilkat-ocean");
let _ = http.set_url_var("object_name", "starfish.jpg");
let url = "https://www.googleapis.com/storage/v1/b/{$bucket_name}/o/{$object_name}?alt=media".to_string();

// If there is an error response, then we didn't actually download the file data,
// but instead we downloaded an error response..
let file_data = chilkat::BinData::new();
if http.download_bd(&url, &file_data).is_err() {
    println!("{}", http.last_error_text());
    return;
}

let sb_error_response = chilkat::StringBuilder::new();
let response_code = http.last_status();
if response_code == 401 {
    println!("If invalid credentials, then it is likely the access token expired.");
    println!("Your app should automatically fetch a new access token and re-try.");
}

if response_code != 200 {
    // Get the error response
    let _ = sb_error_response.append_bd(&file_data, "utf-8", 0, 0);
    println!("Error response code = {}", response_code);
    println!("Error:");
    println!("{}", sb_error_response.get_as_string().unwrap_or_default());
    return;
}

println!("Success.");

// Save the downloaded data to a file.
let _ = file_data.write_file("qa_output/starfish.jpg").is_ok();