Rust
Rust
Upload File from String
See more Google Drive Examples
Uploads a text file where the contents of the file are contained in a string variable.See Google Drive Files: create for more details.
Also See Google Drive Multipart Upload for more details.
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.
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);
// A multipart upload to Google Drive needs a multipart/related Content-Type
let _ = rest.add_header("Content-Type", "multipart/related");
// Specify each part of the request.
// The 1st part is JSON with information about the file.
rest.set_part_selector("1");
let _ = rest.add_header("Content-Type", "application/json; charset=UTF-8");
let json = chilkat::JsonObject::new();
let _ = json.append_string("name", "helloWorld.txt");
let _ = json.append_string("description", "A simple text file that says Hello World.");
let _ = json.append_string("mimeType", "text/plain");
let _ = rest.set_multipart_body_string(&json.emit().unwrap_or_default());
// The 2nd part is the file content.
// In this case, we'll upload a simple text file containing "Hello World!"
rest.set_part_selector("2");
let _ = rest.add_header("Content-Type", "text/plain");
let file_contents = "Hello World!".to_string();
let _ = rest.set_multipart_body_string(&file_contents);
let Ok(json_response) = rest.full_request_multipart("POST", "/upload/drive/v3/files?uploadType=multipart") 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());
println!("response JSON: {}", json_response);
return;
}
// Show the JSON response.
let _ = json.load(&json_response);
// Show the full JSON response.
json.set_emit_compact(false);
println!("{}", json.emit().unwrap_or_default());
// A successful response looks like this:
// {
// "kind": "drive#file",
// "id": "0B53Q6OSTWYoldmJ0Z3ZqT2x5MFk",
// "name": "Untitled",
// "mimeType": "text/plain"
// }
// Get the fileId:
println!("fileId: {}", json.string_of("id").unwrap_or_default());