-
-
Save jhwgh1968/3cd073677f74506474bbcbcadeffb0ee to your computer and use it in GitHub Desktop.
Rust Example for ureq + multipart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A simple file uploader client template with Rust + ureq + multipart | |
// Released into the public domain by its author | |
use std::path::PathBuf; | |
use multipart::client::lazy::Multipart; | |
fn main() { | |
let file_name = PathBuf::from( | |
std::env::args_os() | |
.skip(1) | |
.next() | |
.expect("file name required"), | |
); | |
let post_file = std::fs::File::open(&file_name).expect(&format!("cannot open {:?}", file_name)); | |
let file_extension = file_name.extension().and_then(|s| s.to_str()).unwrap_or(""); | |
let mime = mime_guess::from_ext(&file_extension).first_or_octet_stream(); | |
let mut m = Multipart::new(); | |
m.add_text("key", "value"); | |
m.add_stream("data", post_file, Some("blob"), Some(mime)); | |
let post_url = "http://file-storage.example.com/upload.cgi"; | |
eprintln!("Sending request..."); | |
let mdata = m.prepare().unwrap(); | |
let response = ureq::post(post_url.as_ref()) | |
.set( | |
"Content-Type", | |
&format!("multipart/form-data; boundary={}", mdata.boundary()), | |
) | |
.send(mdata); | |
if let Some(e) = response.synthetic_error() { | |
eprintln!("Upload failed: {}", e); | |
} else { | |
eprintln!("Upload successful."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment