Sample code for 30+ languages & platforms
Rust

S3 Upload the Parts for a Multipart Upload

See more Amazon S3 (new) Examples

This example uploads a large file in parts. The multipart upload needs to have been first initiated prior to uploading the parts.

See http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html for more information about uploading parts.

Chilkat Rust Downloads

Rust

// In the 1st step for uploading a large file, the multipart upload was initiated
// as shown here: Initiate Multipart Upload

// Other S3 Multipart Upload Examples:
// Complete Multipart Upload
// Abort Multipart Upload
// List Parts

// When we initiated the multipart upload, we saved the XML response to a file.  This
// XML response contains the UploadId.  We'll begin by loading that XML and getting
// the Upload ID.

let xml_init = chilkat::Xml::new();
if xml_init.load_xml_file("s3_multipart_uploads/initiate.xml").is_err() {
    println!("Did not find the initiate.xml XML file.");
    return;
}

let upload_id = xml_init.get_child_content("UploadId").unwrap_or_default();
println!("UploadId = {}", upload_id);

// When uploading parts, we need to keep an XML record of each part number
// and its corresponding ETag, which is received in the response for each part.
// There can be up to 10000 parts, numbered 1 to 10000.  
// After all parts have been uploaded, the final step will be to complete
// the multipart upload (see Complete Multipart Upload)

// In this example, the large file we want to upload is somethingBig.zip
let file_to_upload_path = "s3_multipart_uploads/somethingBig.zip".to_string();

// The minimum allowed part size is 5MB (5242880 bytes).  The last part can be smaller because
// it will contain the remainder of the file.  (This minimum is enforced by the AWS service.)
// We'll use the minimum allowed part size for this example.
let part_size = 5242880;

// Let's use Chilkat's FileAccess API to examine the file to be uploaded.  We'll get the size
// of the file and find out how many parts will be needed, including the final "partial" part.
let fac = chilkat::FileAccess::new();
let _ = fac.open_for_read(&file_to_upload_path);

// How many parts will there be if each part is 5242880 bytes?
let num_parts = fac.get_num_blocks(part_size);
println!("numParts = {}", num_parts);
fac.file_close();

// Imagine that we may be running this for the 1st time, or maybe we already
// attempted to upload parts, and something failed. Maybe there was a network problem
// the resulted in not all parts getting uploaded.  We'll write this code so that if run again,
// it will upload whatever parts haven't yet been uploaded.

// We'll keep a partsList.xml file to record the parts that have already been successfully
// uploaded.  If this file does not yet exist, we'll create it..
let parts_list_file = "s3_multipart_uploads/partsList.xml".to_string();
let parts_list_xml = chilkat::Xml::new();
if fac.file_exists(&parts_list_file) {
    let _ = parts_list_xml.load_xml_file(&parts_list_file);
}

// Make sure the top-level tag is "CompleteMultipartUpload"
parts_list_xml.set_tag("CompleteMultipartUpload");

// --------------------------------------
// Before entering the loop to upload parts,
// setup the REST object with AWS authentication,
// and make the initial connection.
let rest = chilkat::Rest::new();

// Connect to the Amazon AWS REST server.
let b_tls = true;
let port = 443;
let b_auto_reconnect = true;
let _ = rest.connect("s3.amazonaws.com", port, b_tls, b_auto_reconnect).is_ok();

// ----------------------------------------------------------------------------
// Important: For buckets created in regions outside us-east-1,
// there are three important changes that need to be made.
// See Working with S3 Buckets in Non-us-east-1 Regions for the details.
// ----------------------------------------------------------------------------

// Provide AWS credentials for the REST call.
let auth_aws = chilkat::AuthAws::new();
auth_aws.set_access_key("AWS_ACCESS_KEY");
auth_aws.set_secret_key("AWS_SECRET_KEY");
auth_aws.set_service_name("s3");
let _ = rest.set_auth_aws(&auth_aws).is_ok();

// Set the bucket name via the HOST header.
// In this case, the bucket name is "chilkat100".
rest.set_host("chilkat100.s3.amazonaws.com");
// --------------------------------------

let mut part_number = 1;
let sb_part_number = chilkat::StringBuilder::new();

while part_number <= num_parts {
    println!("---- {} ----", part_number);

    // This cumbersome way of converting an integer to a string is because
    // Chilkat examples are written in a script that is converted to many programming languages.
    // At this time, the translator does not have integer-to-string code generation capability..
    sb_part_number.clear();
    let _ = sb_part_number.append_int(part_number);

    let mut b_part_already_uploaded = false;

    // If there are no children, then the XML is empty and no parts have yet been uploaded.
    let num_uploaded_parts = parts_list_xml.num_children();
    if num_uploaded_parts > 0 {
        // If some parts have been uploaded, check to see if this particular part was already upload.
        // If so, then it can be skipped.

        // Position ourselves at the 1st record.
        let x_rec0 = parts_list_xml.get_child(0).unwrap();
        if let Ok(found_rec) = x_rec0.find_next_record("PartNumber", &sb_part_number.get_as_string().unwrap_or_default()) {
            b_part_already_uploaded = true;
            println!("Part {} was previously uploaded.", part_number);
            println!("{}", found_rec.get_xml().unwrap_or_default());

        }

    }

    // If this part was not already uploaded, we need to upload.
    // Also update the partsListXml and save as each part is successfully uploaded.
    if !b_part_already_uploaded {
        println!("Uploading part {} ...", part_number);

        // Setup the stream source for the large file to be uploaded..
        let file_stream = chilkat::Stream::new();
        file_stream.set_source_file(&file_to_upload_path);
        // The Chilkat Stream API has features to make uploading a parts
        // of a file easy.  Indicate the part size by setting the SourceFilePartSize
        // property.
        file_stream.set_source_file_part_size(part_size);

        // Our HTTP start line to upload a part will look like this:
        // PUT /ObjectName?partNumber=PartNumber&uploadId=UploadId HTTP/1.1

        // Set the query params.  We'll need partNumber and uploadId.
        // Make sure the query params from previous iterations are clear.
        let _ = rest.clear_all_query_params();
        let _ = rest.add_query_param("partNumber", &sb_part_number.get_as_string().unwrap_or_default());
        let _ = rest.add_query_param("uploadId", &upload_id);

        // Upload this particular file part.
        // Tell the fileStream which part is being uploaded.
        // Our partNumber is 1-based (the 1st part is at index 1), but the fileStream's SourceFilePart
        // property is 0-based.  Therefore we use partNumber-1.
        file_stream.set_source_file_part(part_number - 1);

        // Because the SourceFilePart and SourceFilePartSize properties are set, the stream will 
        // will provide just that part of the file.  
        let Ok(response_str) = rest.full_request_stream("PUT", "/somethingBig.zip", &file_stream) else {
            println!("{}", rest.last_error_text());
            return;
        };

        if rest.response_status_code() != 200 {
            // Examine the request/response to see what happened.
            println!("response status code = {}", rest.response_status_code());
            println!("response status text = {}", rest.response_status_text());
            println!("response header: {}", rest.response_header());
            println!("response body: {}", response_str);
            println!("---");
            println!("LastRequestStartLine: {}", rest.last_request_start_line());
            println!("LastRequestHeader: {}", rest.last_request_header());
            return;
        }

        // OK, this part was uploaded..
        // The response will have a 0-length body.  The only information we need is the 
        // ETag response header field.
        // It should be present, but just in case there was no ETag header...
        let Ok(etag) = rest.response_hdr_by_name("ETag") else {
            println!("No ETag response header found!");
            println!("response header: {}", rest.response_header());
            return;
        };

        // We need to add record to the partsListXml.
        // The record will look like this:
        // &lt;Part>
        //   &lt;PartNumber>PartNumber&lt;/PartNumber>
        //   &lt;ETag>ETag&lt;/ETag>
        // &lt;/Part>
        let x_part = parts_list_xml.new_child("Part", "").unwrap();
        x_part.new_child_int2("PartNumber", part_number);
        x_part.new_child2("ETag", &etag);

        if parts_list_xml.save_xml(&parts_list_file).is_err() {
            println!("{}", parts_list_xml.last_error_text());
            return;
        }

        println!("-- Part {} uploaded. ---------------------", part_number);
    }

    part_number = part_number + 1;
}

println!("Finished.  All parts uploaded.");