2

我正在按照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,但损坏的文件问题仍然存在

我在代码中遗漏了什么吗?

4

2 回答 2

4

只需使用bytesCursor工作,它就更简单了:

let mut content =  Cursor::new(response.bytes().await?);
copy(&mut content, &mut dest)?;
于 2020-09-14T09:32:58.297 回答
2

更换

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

经过

let content =  response.bytes().await?;
    
let mut pos = 0;
while pos < content.len() {
    let bytes_written = dest.write(&content[pos..])?;
    pos += bytes_written;
}

工作!:)

如果此代码效率低下,请回复感谢大家的帮助。

于 2020-09-14T09:10:20.227 回答