Rust Requires Chilkat v11.7.0+
Rust
Box: Upload a Large File in Parts and Commit the Session
See more Box Examples
Run the reusable setup once per HttpCurl object, then select names and execute the operation. The setup is repeated here only to make this published example independently runnable. Resolve documents by name, then perform the explicit chunked-upload session, part, and commit loop. Supports 20 MB through 2 GB using int. Saves recovery information and honors bounded commit Retry-After.
See the Box API guide for setup and the complete workflow.
Chilkat Rust Downloads
let mut success = false;
// Requires Chilkat 11.7.0 or later and a previously unlocked Chilkat bundle.
// See Global Unlock Sample.
// Guide: Box API Guide.
success = false;
// BEGIN ONE-TIME SETUP
// This block is repeated so each published example can run on its own.
// In an application, run the setup example once and pass the SAME curl object
// to operation code below. Do not recreate it for every operation.
// See Reusable Box HttpCurl Setup.
let curl = chilkat::HttpCurl::new();
curl.set_var("access_token", "BOX_ACCESS_TOKEN");
curl.set_var("parent_name", "/");
// Box's fixed root ID is an implementation detail; callers supply names.
curl.set_var("parent_id", "0");
let setup_command = chilkat::StringBuilder::new();
// Register findParent; registration sends no request.
let _ = setup_command.set_string("curl -X GET \"https://api.box.com/2.0/folders/0/items?limit=1000&fields=id,type,name\" -H \"Authorization: Bearer ACCESS_TOKEN\"");
let _ = setup_command.replace("ACCESS_TOKEN", &curl.get_var("access_token").unwrap_or_default());
success = curl.add_function("findParent", &setup_command.get_as_string().unwrap_or_default()).is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
// Register findFolder; registration sends no request.
let _ = setup_command.set_string("curl -X GET \"https://api.box.com/2.0/folders/{{parent_id}}/items?limit=1000&fields=id,type,name\" -H \"Authorization: Bearer ACCESS_TOKEN\"");
let _ = setup_command.replace("ACCESS_TOKEN", &curl.get_var("access_token").unwrap_or_default());
success = curl.add_function("findFolder", &setup_command.get_as_string().unwrap_or_default()).is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
// Register findFile; registration sends no request.
let _ = setup_command.set_string("curl -X GET \"https://api.box.com/2.0/folders/{{folder_id}}/items?limit=1000&fields=id,type,name\" -H \"Authorization: Bearer ACCESS_TOKEN\"");
let _ = setup_command.replace("ACCESS_TOKEN", &curl.get_var("access_token").unwrap_or_default());
success = curl.add_function("findFile", &setup_command.get_as_string().unwrap_or_default()).is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
// Register findDestination; registration sends no request.
let _ = setup_command.set_string("curl -X GET \"https://api.box.com/2.0/folders/0/items?limit=1000&fields=id,type,name\" -H \"Authorization: Bearer ACCESS_TOKEN\"");
let _ = setup_command.replace("ACCESS_TOKEN", &curl.get_var("access_token").unwrap_or_default());
success = curl.add_function("findDestination", &setup_command.get_as_string().unwrap_or_default()).is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
// Register getFileDetails; registration sends no request.
let _ = setup_command.set_string("curl -X GET \"https://api.box.com/2.0/files/{{file_id}}?fields=id,sha1,file_version\" -H \"Authorization: Bearer ACCESS_TOKEN\"");
let _ = setup_command.replace("ACCESS_TOKEN", &curl.get_var("access_token").unwrap_or_default());
success = curl.add_function("getFileDetails", &setup_command.get_as_string().unwrap_or_default()).is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
// Register getEnterprise; registration sends no request.
let _ = setup_command.set_string("curl -X GET \"https://api.box.com/2.0/users/me?fields=enterprise\" -H \"Authorization: Bearer ACCESS_TOKEN\"");
let _ = setup_command.replace("ACCESS_TOKEN", &curl.get_var("access_token").unwrap_or_default());
success = curl.add_function("getEnterprise", &setup_command.get_as_string().unwrap_or_default()).is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
// Register output rules once. Chilkat 11.7.0 evaluates {{name}} variables
// when extracting each output, using the current value at that time.
success = curl.add_output2("findParent", "entries", "name", "{{parent_name}}", true, "id", "parent_id").is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
success = curl.add_output2("findFolder", "entries", "name", "{{folder_name}}", true, "id", "folder_id").is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
success = curl.add_output2("findFile", "entries", "name", "{{file_name}}", true, "id", "file_id").is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
success = curl.add_output2("findDestination", "entries", "name", "{{destination_name}}", true, "id", "destination_id").is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
success = curl.add_output("getFileDetails", "file_version.id", "file_version_id").is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
success = curl.add_output("getFileDetails", "sha1", "file_sha1").is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
success = curl.add_output("getEnterprise", "enterprise.id", "enterprise_id").is_ok();
if !success {
println!("{}", curl.last_error_text());
return;
}
// END ONE-TIME SETUP
// The name lookups below assume each listing fits in one page (1000 items).
// Parent and destination names select root children; folder_name selects a child
// of parent_name. "/" selects the root parent. These are not arbitrary paths.
// BEGIN OPERATION -- keep the configured object when reusing it.
// Inputs are names. Retain cached IDs when the selected names have not changed.
let parent_name = "/".to_string();
let folder_name = "documents".to_string();
if (curl.get_var("parent_name").unwrap_or_default() != parent_name) || ((parent_name == "/") && (!curl.var_defined("parent_id"))) {
curl.set_var("parent_name", &parent_name);
curl.clear_var("parent_id");
curl.clear_var("folder_id");
curl.clear_var("file_id");
curl.clear_var("file_version_id");
curl.clear_var("file_sha1");
if parent_name == "/" {
curl.set_var("parent_id", "0");
}
}
if curl.get_var("folder_name").unwrap_or_default() != folder_name {
curl.set_var("folder_name", &folder_name);
curl.clear_var("folder_id");
curl.clear_var("file_id");
curl.clear_var("file_version_id");
curl.clear_var("file_sha1");
}
// Resolve the named destination first. HttpCurl does not expand variables
// inside multipart -F attributes in the tested build, so this upload is two phases.
curl.clear_target_output("*");
let authorized_command1 = chilkat::StringBuilder::new();
let _ = authorized_command1.set_string("curl -X GET \"https://api.box.com/2.0/folders/{{folder_id}}?fields=id\" -H \"Authorization: Bearer {{access_token}}\"");
let header_replacement1 = authorized_command1.replace("{{access_token}}", &curl.get_var("access_token").unwrap_or_default());
success = curl.do_your_thing(&authorized_command1.get_as_string().unwrap_or_default()).is_ok();
if (!success) || (curl.status_code() != 200) {
println!("Box request failed. HTTP status: {}", curl.status_code());
println!("Failure reason: {}", curl.fail_reason());
println!("{}", curl.response_body_str());
return;
}
// This example limits size to 2 GB so offsets fit all generated languages' integers.
// The source must not change during hashing or upload. Create qa_output first.
let local_path = "qa_data/large-document.zip".to_string();
let file = chilkat::FileAccess::new();
// Check the decimal size before converting so an oversized file cannot overflow int.
let Ok(size_string) = file.file_size_str(&local_path) else {
println!("{}", file.last_error_text());
return;
};
let size_text = chilkat::StringBuilder::new();
let _ = size_text.set_string(&size_string);
let size_match = chilkat::JsonObject::new();
if size_text.regex_match("^([0-9]{1,9}|1[0-9]{9}|2000000000)$", &size_match, 100) != 1 {
println!("Choose an input between 20 MB and 2 GB for this example.");
return;
}
let file_size = size_string.parse::<i32>().unwrap_or(0);
if file_size < 20971520 {
println!("Choose an input between 20 MB and 2 GB for this example.");
return;
}
let http = chilkat::Http::new();
http.set_auth_token(&curl.get_var("access_token").unwrap_or_default());
let response = chilkat::HttpResponse::new();
let request = chilkat::JsonObject::new();
let _ = request.update_string("folder_id", &curl.get_var("folder_id").unwrap_or_default());
let _ = request.update_string("file_name", "large-document.zip");
let _ = request.update_int("file_size", file_size);
success = http.http_json("POST", "https://upload.box.com/api/2.0/files/upload_sessions", &request, "application/json", &response).is_ok();
if !success {
println!("{}", http.last_error_text());
return;
}
if response.status_code() != 201 {
println!("{}", response.body_str());
return;
}
let session = chilkat::JsonObject::new();
success = session.load(&response.body_str()).is_ok();
if !success {
println!("{}", session.last_error_text());
return;
}
success = session.write_file("qa_output/box_upload_session.json").is_ok();
if !success {
println!("{}", session.last_error_text());
return;
}
let part_size = session.int_of("part_size");
let upload_url = session.string_of("session_endpoints.upload_part").unwrap_or_default();
let commit_url = session.string_of("session_endpoints.commit").unwrap_or_default();
if (part_size <= 0) || ((upload_url == "") || (commit_url == "")) {
println!("Invalid session response.");
return;
}
let hash = chilkat::Crypt2::new();
hash.set_hash_algorithm("sha1");
hash.set_encoding_mode("base64");
let Ok(file_digest) = hash.hash_file_enc(&local_path) else {
println!("{}", hash.last_error_text());
return;
};
success = file.file_open(&local_path, 2147483648, 1, 3, 0).is_ok();
if !success {
println!("{}", file.last_error_text());
return;
}
let commit = chilkat::JsonObject::new();
let part_response = chilkat::JsonObject::new();
let chunk = chilkat::BinData::new();
let range = chilkat::StringBuilder::new();
let digest_header = chilkat::StringBuilder::new();
let mut offset = 0;
let mut part_index = 0;
let mut part_length: i32 = 0;
let mut last_byte: i32 = 0;
let mut part_digest = String::new();
while offset < file_size {
let _ = chunk.clear();
success = file.file_read_bd(part_size, &chunk).is_ok();
if !success {
println!("{}", file.last_error_text());
file.file_close();
return;
}
part_length = chunk.num_bytes();
if part_length <= 0 {
println!("Unexpected end of file.");
file.file_close();
return;
}
last_byte = offset + (part_length - 1);
range.clear();
let _ = range.append("bytes ");
let _ = range.append_int(offset);
let _ = range.append("-");
let _ = range.append_int(last_byte);
let _ = range.append("/");
let _ = range.append_int(file_size);
part_digest = hash.hash_bd_enc(&chunk).unwrap_or_default();
if !hash.last_method_success() {
println!("{}", hash.last_error_text());
file.file_close();
return;
}
let _ = digest_header.set_string("sha=");
let _ = digest_header.append(&part_digest);
http.set_request_header("Digest", &digest_header.get_as_string().unwrap_or_default());
http.set_request_header("Content-Range", &range.get_as_string().unwrap_or_default());
success = http.http_bd("PUT", &upload_url, &chunk, "application/octet-stream", &response).is_ok();
if (!success) || (response.status_code() != 200) {
println!("Part failed. HTTP status: {}", response.status_code());
println!("{}", response.body_str());
println!("Inspect the saved session and server list_parts before retrying this part.");
file.file_close();
return;
}
if part_response.load(&response.body_str()).is_err() {
file.file_close();
return;
}
commit.set_i(part_index);
// Copy the server's acknowledged part fields into the commit manifest.
let _ = commit.update_string("parts[i].part_id", &part_response.string_of("part.part_id").unwrap_or_default());
let _ = commit.update_int("parts[i].offset", part_response.int_of("part.offset"));
let _ = commit.update_int("parts[i].size", part_response.int_of("part.size"));
let _ = commit.update_string("parts[i].sha1", &part_response.string_of("part.sha1").unwrap_or_default());
if commit.write_file("qa_output/box_upload_parts.json").is_err() {
println!("{}", commit.last_error_text());
file.file_close();
return;
}
offset = offset + part_length;
part_index = part_index + 1;
}
file.file_close();
http.remove_request_header("Content-Range");
let _ = digest_header.set_string("sha=");
let _ = digest_header.append(&file_digest);
http.set_request_header("Digest", &digest_header.get_as_string().unwrap_or_default());
let mut attempts = 0;
let mut wait_seconds: i32 = 0;
let retry_header = chilkat::StringBuilder::new();
let retry_match = chilkat::JsonObject::new();
let mut completed = false;
while (attempts < 10) && (!completed) {
if http.http_json("POST", &commit_url, &commit, "application/json", &response).is_err() {
println!("Commit failed: {}", response.status_code());
println!("{}", response.body_str());
return;
}
if response.status_code() == 201 {
completed = true;
} else {
if response.status_code() != 202 {
println!("Unexpected commit status: {}", response.status_code());
return;
}
// Box's asynchronous commit response supplies Retry-After in seconds.
let _ = retry_header.set_string(&response.get_header_field("Retry-After").unwrap_or_default());
if retry_header.regex_match("^[0-9]{1,2}$", &retry_match, 100) != 1 {
println!("Commit pending. Preserve the session and inspect Retry-After before resuming: {}", retry_header.get_as_string().unwrap_or_default());
return;
}
wait_seconds = retry_header.get_as_string().unwrap_or_default().parse::<i32>().unwrap_or(0);
if (wait_seconds < 1) || (wait_seconds > 60) {
println!("Commit pending. Resume commit after Retry-After: {}", response.get_header_field("Retry-After").unwrap_or_default());
return;
}
http.sleep_ms(wait_seconds * 1000);
}
attempts = attempts + 1;
}
if !completed {
println!("Commit still pending; retain session and part manifests to resume commit later.");
return;
}
println!("Upload committed: {}", response.body_str());