seanmonstar / reqwest

An easy and powerful Rust HTTP Client
https://docs.rs/reqwest
Apache License 2.0
9.99k stars 1.13k forks source link

Add example for saving file to the filesystem #1266

Open sffc opened 3 years ago

sffc commented 3 years ago

It would be a time-saver if an example showing how to download a file and save it to the filesystem could be added to the reqwest docs.

I came up with the following, based on .bytes_stream(), but I don't know if it's optimal:

use futures_util::StreamExt;
use tokio::io::AsyncWriteExt;

let mut stream = self.client.get(url).send().await?.bytes_stream();
let mut file = tokio::fs::File::create(path).await?;
while let Some(item) = stream.next().await {
    file.write_buf(&mut item?).await?;
}
midnightexigent commented 3 years ago

Giving this a bump

It would be nice to have an example

Xunjin commented 3 years ago

Nice! This actually saved my life, struggle 2 days (yeah.. I'm still a newbie with Rust :sob:) trying to file a suitable async way to save/download on disk.

Also, maybe we could open a broad issue with usage cases with reqwest to add to the docs?

Rocket did sort of this here https://github.com/SergioBenitez/Rocket/issues/1585

OP should really open a PR with this example, thank you so much (again!)

adumbidiot commented 3 years ago

Shouldn't that be a write_all_buf?

Xunjin commented 3 years ago

Yes @adumbidiot I had some problems with write_buf and forgot to add that write_all_buf solved them.

jtara1 commented 2 years ago

Alternatively, you can do the same but with the chunk method.

use std::borrow::BorrowMut;
use tokio::io::AsyncWriteExt;

let mut response = client.get(dbg!(url)).send().await?;
let mut file = tokio::fs::File::create(path).await?;

while let Some(mut item) = response.chunk().await? {
    file.write_all_buf(item.borrow_mut()).await?;
}