Qwe*_*tie 8 rust rust-tokio reqwest
我正在尝试将使用 reqwest 下载的文件复制到 tokio 文件中。该文件太大,无法存储在内存中,因此需要通过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?;
Run Code Online (Sandbox Code Playgroud)
这失败了,因为
|
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
Run Code Online (Sandbox Code Playgroud)
有什么方法可以在流上获取特征 AsyncRead 或以其他方式将此数据复制到文件中?我使用 tokio 文件的原因是我稍后需要从中进行 AsyncRead 。也许复制到常规 std::File 然后将其转换为 tokio::fs::File 是有意义的?
这个方法有效。松散地基于以下示例bytes_stream()
注意:您可能想在此处缓冲写入
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?;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1850 次 |
| 最近记录: |