rust-lang-nursery / rust-cookbook

https://rust-lang-nursery.github.io/rust-cookbook
Creative Commons Zero v1.0 Universal
2.24k stars 286 forks source link

Download example using `response.bytes()` instead of `response.text()` #670

Open frantufro opened 2 years ago

frantufro commented 2 years ago

The current example for downloading files interprets the response as text, and then turns it into bytes.

let content = response.text().await?;
copy(&mut content.as_bytes(), &mut dest)?;

This is fine if you're downloading text files, but it will corrupt binary files (I found this issue when downloading PNGs).

In order to fix this I suggest using response.bytes() directly.

let content = response.bytes().await?;
dest.write(&content)?;

This is how I ended up implementing it and it works great.