Skip to content

Instantly share code, notes, and snippets.

@jhwgh1968
Created November 5, 2020 00:45
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhwgh1968/3cd073677f74506474bbcbcadeffb0ee to your computer and use it in GitHub Desktop.
Save jhwgh1968/3cd073677f74506474bbcbcadeffb0ee to your computer and use it in GitHub Desktop.
Rust Example for ureq + multipart
// 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