rust 将请求字节流复制到时雄文件中

to94eoyn  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(131)

我正在尝试将reqwest下载的文件复制到时雄文件中。此文件太大,无法存储在内存中,因此需要通过bytes_stream()而不是bytes()
我尝试了以下几点

let mut tmp_file = tokio::fs::File::from(tempfile::tempfile()?);
let byte_stream = reqwest::get(&link).await?.bytes_stream();
tokio::io::copy(&mut byte_stream, &mut tmp_file).await?;

失败的原因是

|
153 |     tokio::io::copy(&mut byte_stream, &mut tmp_file).await?;
    |     --------------- ^^^^^^^^^^^^^^^^ the trait `tokio::io::AsyncRead` is not implemented for `impl Stream<Item = Result<bytes::bytes::Bytes, reqwest::Error>>`
    |     |
    |     required by a bound introduced by this call

有没有什么方法可以让我在Stream上获得AsyncRead特征或者将这些数据复制到文件中?我使用时雄文件的原因是我以后需要从它进行AsyncRead。也许复制到一个常规的std::File中然后将其转换为tokio::fs::File会有意义?

qhhrdooz

qhhrdooz1#

这个方法是可行的。
注意:您可能希望在此处缓冲写入

use futures::StreamExt;

let mut tmp_file = tokio::fs::File::from(tempfile::tempfile()?);
let mut byte_stream = reqwest::get(&link).await?.bytes_stream();

while let Some(item) = byte_stream.next().await {
  tokio::io::copy(&mut item?.as_ref(), &mut tmp_file).await?;
}

相关问题