我正在按照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,但损坏的文件问题仍然存在
我在代码中遗漏了什么吗?