Skip to content

Commit

Permalink
update image_download.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
raghav-rama committed Feb 29, 2024
1 parent d2d21d9 commit e41df37
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions src/bin/image_download.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,34 @@
fn main() {
println!("Download an image from the web using reqwest");
use error_chain::error_chain;
use std::{fs::File, io::copy};
use tempfile::Builder;

error_chain! {
foreign_links {
Io(std::io::Error);
HttpRequest(reqwest::Error);
}
}

#[tokio::main]
async fn main() -> Result<()> {
let tmp_dir = Builder::new().prefix("image_download").tempdir()?;
let target = String::from("https://www.rust-lang.org/logos/rust-logo-512x512.png");
let response = reqwest::get(&target).await?;
let mut destination = {
let file_name = response
.url()
.path_segments()
.and_then(|segments| segments.last())
.and_then(|name| if name.is_empty() { None } else { Some(name) })
.unwrap_or("tmp.bin");
println!("File to download: '{}'", file_name);
let file_name = tmp_dir.path().join(file_name);
println!("Located at: '{:?}'", file_name);
File::create(file_name)?
};
let tmp_dir = tmp_dir.into_path();
println!("Temp directory: '{:?}'", tmp_dir);
let content = response.bytes().await?;
copy(&mut content.as_ref(), &mut destination)?;
Ok(())
}

0 comments on commit e41df37

Please sign in to comment.