reqwest icon indicating copy to clipboard operation
reqwest copied to clipboard

Add example for saving file to the filesystem

Open sffc opened this issue 4 years ago • 5 comments

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?;
}

sffc avatar May 05 '21 00:05 sffc

Giving this a bump

It would be nice to have an example

midnightexigent avatar Jun 27 '21 00:06 midnightexigent

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!)

Xunjin avatar Jul 07 '21 15:07 Xunjin

Shouldn't that be a write_all_buf?

adumbidiot avatar Jul 18 '21 23:07 adumbidiot

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

Xunjin avatar Jul 19 '21 12:07 Xunjin

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?;
}

jtara1 avatar Apr 22 '22 08:04 jtara1