Rust
Rust
Write Bytes to a Remote SFTP File (BinData)
See more SFTP Examples
Demonstrates the Chilkat SFtp.WriteFileBd method, which appends all bytes in a BinData to the remote file identified by an open handle. The first argument is the handle and the second is the BinData.
Note: This example uses a relative local path, which is resolved against the application's current working directory. Absolute local paths may also be used. Supply the path appropriate to your own environment.
Background: This is the binary counterpart to
WriteFileText — the right choice for images, archives, or any non-text content, where a charset conversion would corrupt the data. Combined with an appropriate OpenFile disposition it can create, overwrite, or append; here the file is created/truncated first so the result is exactly the BinData contents.Chilkat Rust Downloads
// Demonstrates the SFtp.WriteFileBd method, which appends all bytes in a BinData to the remote
// file identified by an open handle. The 1st argument is the handle and the 2nd is the BinData.
let sftp = chilkat::SFtp::new();
// Connect, authenticate, and initialize the SFTP subsystem.
let port = 22;
if sftp.connect("sftp.example.com", port).is_err() {
println!("{}", sftp.last_error_text());
return;
}
// Normally you would not hard-code the password in source. You should instead obtain it
// from an interactive prompt, environment variable, or a secrets vault.
let password = "mySshPassword".to_string();
if sftp.authenticate_pw("mySshLogin", &password).is_err() {
println!("{}", sftp.last_error_text());
return;
}
if sftp.initialize_sftp().is_err() {
println!("{}", sftp.last_error_text());
return;
}
// Open (creating/truncating) the remote file for writing.
let Ok(handle) = sftp.open_file("subdir/image.png", "writeOnly", "createTruncate") else {
println!("{}", sftp.last_error_text());
return;
};
// Put the bytes to write into a BinData. (Here they are loaded from a local file, but the
// bytes could come from anywhere.)
let bd = chilkat::BinData::new();
if bd.load_file("qa_data/image.png").is_err() {
println!("{}", bd.last_error_text());
return;
}
// Append the BinData bytes to the open remote file.
if sftp.write_file_bd(&handle, &bd).is_err() {
println!("{}", sftp.last_error_text());
return;
}
if sftp.close_handle(&handle).is_err() {
println!("{}", sftp.last_error_text());
return;
}
println!("Wrote {} bytes.", bd.num_bytes());
sftp.disconnect();