reqwest
reqwest copied to clipboard
Add example for saving file to the filesystem
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?;
}
Giving this a bump
It would be nice to have an example
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!)
Shouldn't that be a write_all_buf?
Yes @adumbidiot I had some problems with write_buf and forgot to add that write_all_buf solved them.
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?;
}