【发布时间】:2020-09-14 20:00:08
【问题描述】:
我正在按照 https://rust-lang-nursery.github.io/rust-cookbook/web/clients/download.html 的 Rust Cookbook 中提到的代码通过 HTTP GET 请求以异步方式下载文件。
我的代码如下:
#[tokio::main]
async fn main() -> Result<()> {
let object_path = "logos/rust-logo-512x512.png";
let target = format!("https://www.rust-lang.org/{}", object_path);
let response = reqwest::get(&target).await?;
let mut dest = {
let fname = response
.url()
.path_segments()
.and_then(|segments| segments.last())
.and_then(|name| if name.is_empty() { None } else { Some(name) })
.unwrap_or("tmp.bin");
println!("file to download: '{}'", fname);
let object_prefix = &object_path[..object_path.rfind('/').unwrap()];
let object_name = &object_path[object_path.rfind('/').unwrap()+1..];
let output_dir = format!("{}/{}", env::current_dir().unwrap().to_str().unwrap().to_string(), object_prefix);
fs::create_dir_all(output_dir.clone())?;
println!("will be located under: '{}'", output_dir.clone());
let output_fname = format!("{}/{}", output_dir, object_name);
println!("Creating the file {}", output_fname);
File::create(output_fname)?
};
let content = response.text().await?;
copy(&mut content.as_bytes(), &mut dest)?;
Ok(())
}
它创建目录并下载文件。 但是,当我打开文件时,它显示损坏的文件错误 我也尝试过使用其他一些 URL,但损坏的文件问题仍然存在
我在代码中遗漏了什么吗?
【问题讨论】:
-
您正在以文本形式下载响应,因此它自然不会工作,因为 PNG 文件是二进制文件。
-
使用
bytes而不是text -
我试过
let content = response.bytes().await?; copy(&mut content, &mut dest)?;但它给出了错误``` copy(&mut content, &mut dest)?;没有为 bytes::bytes::Bytes ``` 实现特征 std::io::Read -
@test,使用
io::Cursor
标签: rust async-await http-get reqwest