Rust下载并保存ZIP文件

5

我正在尝试下载和保存一个Zip文件。看起来下载正常,但保存时出现问题。如果我尝试解压缩文件,就会出现以下错误:

Archive:  download.zip
error [download.zip]:  missing 3208647056 bytes in zipfile
  (attempting to process anyway)
error [download.zip]:  attempt to seek before beginning of zipfile
  (please check that you have transferred or created the zipfile in the
  appropriate BINARY mode and that you have compiled UnZip properly)

这是我正在使用的代码:

cargo.toml


# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
reqwest = { version = "0.10"}
tokio = { version = "0.2", features = ["full"] }
error-chain = "0.12.2"

src/main.rs

use error_chain::error_chain;
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;

error_chain! {
     foreign_links {
         Io(std::io::Error);
         HttpRequest(reqwest::Error);
     }
}

#[tokio::main]
async fn main() -> Result<()> {
    let target = "https://github.com/twbs/bootstrap/archive/v4.0.0.zip";
    let response = reqwest::get(target).await?;

    let path = Path::new("./download.zip");

    let mut file = match File::create(&path) {
        Err(why) => panic!("couldn't create {}", why),
        Ok(file) => file,
    };
    let content =  response.text().await?;
    file.write_all(content.as_bytes())?;
    Ok(())
}

有人能帮我吗?


还要注意的是,由于std类型都是阻塞的,因此在这里实际上不会异步执行任何操作。 - mcarton
谢谢,你说得对。我不知道为什么没看到这个!现在它可以工作了。 - Debru
1个回答

9
reqwest::Response::text 方法会尝试解析请求正文并用替换字符(REPLACEMENT CHARACTER)代替任何无效的UTF-8序列。对于二进制文件,这将导致文件损坏。

相反,您需要使用reqwest::Response::bytes方法,该方法原样返回内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接