Last active
July 20, 2022 18:32
-
-
Save gschoeni/d9480fbcc56dd02722db6b1a0b916e9b to your computer and use it in GitHub Desktop.
Example HTTP upload with progress using reqwest and indicatif
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
// Read data into buffer | |
let path = std::path::Path::new("/path/to/your/file.zip"); | |
let buffer: Vec<u8> = std::fs::read(path)?; | |
println!("Uploading {} bytes from {:?}", buffer.len(), path); | |
// Create the struct to hold onto and update the progress | |
let upload_progress = indicatif::ProgressBar::new(buffer.len() as u64); | |
let cursor = std::io::Cursor::new(Vec::from(buffer)); | |
let upload_source = ReadProgress { | |
progress_bar: upload_progress, | |
inner: cursor, | |
}; | |
// Build the HTTP request | |
let url = "http://0.0.0.0:3030/upload"; | |
let client = reqwest::blocking::Client::builder() | |
.build()?; | |
// Send HTTP request | |
match client | |
.post(url) | |
// Wrap the upload_source in the body to be read from | |
.body(reqwest::blocking::Body::new(upload_source)) | |
.send() | |
{ | |
Ok(res) => { | |
let status = res.status(); | |
let body = res.text()?; | |
println!("Upload got response[{}]\n{}", status, body); | |
}, | |
Err(err) => { | |
eprintln!("Error uploading file: {}", err); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment