Rust
Rust
Download File (Stream to Local Filesystem)
See more Google Drive Examples
This example demonstrates how to download the content of a file from Google Drive. The file is streamed to the local filesystem.Chilkat Rust Downloads
let _ = true;
// It 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
// Google Drive scope.
let g_auth = chilkat::AuthGoogle::new();
g_auth.set_access_token("GOOGLE_DRIVE_ACCESS_TOKEN");
let rest = chilkat::Rest::new();
// Connect using TLS.
// A single REST object, once connected, can be used for many Google Drive REST API calls.
// The auto-reconnect indicates that if the already-established HTTPS connection is closed,
// then it will be automatically re-established as needed.
let b_auto_reconnect = true;
let _ = rest.connect("www.googleapis.com", 443, true, b_auto_reconnect).is_ok();
// Provide the authentication credentials (i.e. the access token)
let _ = rest.set_auth_google(&g_auth);
// ------------------------------------------------------------------------------
// To download a file, we must know the file ID.
// In a previous example (see Build Local Metadata Cache
// we built a local cache to make it easy to lookup file IDs given a file path.
// Let's say we want to download "testFolder/abc/123/penguins.jpg".
// First we lookup the fileId in the cache. With the fileId, we can download the file.
let gd_cache = chilkat::Cache::new();
gd_cache.set_level(0);
gd_cache.add_root("C:/ckCache/googleDrive");
let Ok(file_id) = gd_cache.fetch_text("testFolder/abc/123/penguins.jpg") else {
println!("Filepath not found in cache.");
return;
};
// We need to send a GET request like this:
// GET https://www.googleapis.com/drive/v3/files/fileId?alt=media
// The fileId is part of the path.
let sb_path = chilkat::StringBuilder::new();
let _ = sb_path.append("/drive/v3/files/");
let _ = sb_path.append(&file_id);
let _ = rest.add_query_param("alt", "media");
// Create a stream object with a SinkFile set to the path where the downloaded file will go.
let file_stream = chilkat::Stream::new();
file_stream.set_sink_file("qa_output/penguins.jpg");
// Indicate that the response body should stream directly to fileStream,
// but only if the response status is 200.
let _ = rest.set_response_body_stream(200, true, &file_stream);
// Download the file, streaming the content to the SinkFile.
let Ok(json_response) = rest.full_request_no_body("GET", &sb_path.get_as_string().unwrap_or_default()) else {
println!("{}", rest.last_error_text());
return;
};
// A successful response will have a status code equal to 200.
if rest.response_status_code() != 200 {
println!("response status code = {}", rest.response_status_code());
println!("response status text = {}", rest.response_status_text());
println!("response header: {}", rest.response_header());
return;
}
println!("File downloaded.");