How to download binary file in Rust by reqwest

reqwest in Rust allows you to download file. The question is how to store the file on the filesystem. There are several examples on the internet where authors are calling .text() which will result in a corrupted file on the filesystem because text() is decoding UTF-8 characters.

Here is an example of how to download a binary file and store content in a file on the local file system.

File download.rs:

use std::io::Cursor;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;

async fn fetch_url(url: String, file_name: String) -> Result<()> {
    let response = reqwest::get(url).await?;
    let mut file = std::fs::File::create(file_name)?;
    let mut content =  Cursor::new(response.bytes().await?);
    std::io::copy(&mut content, &mut file)?;
    Ok(())
}

#[tokio::main]
async fn main() {
    fetch_url("https://georgik.rocks/wp-content/uploads/sianim.gif".to_string(), "siriel.gif".to_string()).await.unwrap();
}

File Cargo.toml:

[package]
name = "download"
version = "0.1.0"
authors = ["Georgik.Rocks"]
edition = "2018"

[dependencies]
reqwest = "*"
tokio = { version = "1", features = ["full"] }

[[bin]]
name = "download"
path = "download.rs"

To build the example type following:

cargo run

24. March 2021 at 21:13 - Software engineering (Tags: , , ). Both comments and pings are currently closed.

Comments are closed.