I am following the code mentioned in Rust Cookbook at https://rust-lang-nursery.github.io/rust-cookbook/web/clients/download.html to download a file in async way by HTTP GET request.
My code is as follows:
#[tokio::main]
async fn main() -> Result<()> {
let object_path = "logos/rust-logo-512x512.png";
let target = format!("https://www.rust-lang.org/{}", object_path);
let response = reqwest::get(&target).await?;
let mut dest = {
let fname = 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: '{}'", fname);
let object_prefix = &object_path[..object_path.rfind('/').unwrap()];
let object_name = &object_path[object_path.rfind('/').unwrap()+1..];
let output_dir = format!("{}/{}", env::current_dir().unwrap().to_str().unwrap().to_string(), object_prefix);
fs::create_dir_all(output_dir.clone())?;
println!("will be located under: '{}'", output_dir.clone());
let output_fname = format!("{}/{}", output_dir, object_name);
println!("Creating the file {}", output_fname);
File::create(output_fname)?
};
let content = response.text().await?;
copy(&mut content.as_bytes(), &mut dest)?;
Ok(())
}
It creates the directories & downloads the file. However, when I open the file, it displays corrupt file error I have tried to use some other URL also, but the corrupt file issue is still there
Am I missing something in the code?
Just using
bytes
andCursor
work too, and it is simpler: