Sample code for 30+ languages & platforms
Rust

Google Drive Multipart Upload String

See more REST Examples

Demonstrates a file upload to Google Drive where the contents of the file are contained in a string variable.

Chilkat Rust Downloads

Rust

// This example will upload a file to Google Drive.
let _ = true;

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

let g_auth = chilkat::AuthGoogle::new();
g_auth.set_scope("https://www.googleapis.com/auth/drive");
g_auth.set_sub_email_address("some.user@example.com");
g_auth.set_expire_num_seconds(3600);

// Obtain an access token as shown in one of the following examples:
// See Get Access Token using a Service Account JSON Key
// See Get Access Token using a P12 File

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 key)
let _ = rest.set_auth_google(&g_auth).is_ok();

// A multipart upload to Google Drive needs a multipart/related Content-Type
let _ = rest.add_header("Content-Type", "multipart/related").is_ok();

// 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").is_ok();

let json = chilkat::JsonObject::new();
let _ = json.add_string_at(-1, "title", "helloWorld.txt").is_ok();
let _ = json.add_string_at(-1, "description", "A simple text file that says Hello World.").is_ok();
let _ = json.add_string_at(-1, "mimeType", "text/plain").is_ok();
let _ = rest.set_multipart_body_string(&json.emit().unwrap_or_default()).is_ok();

// 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").is_ok();
let _ = rest.set_multipart_body_string("Hello World!").is_ok();

// POST https://www.googleapis.com/upload/drive/v2/files
let Ok(json_response) = rest.full_request_multipart("POST", "/upload/drive/v2/files?uploadType=multipart") else {
    println!("{}", rest.last_error_text());
    return;
};

// Show the JSON response.
println!("Response Status Code: {}", rest.response_status_code());
println!("Json Response: {}", json_response);