2

我正在尝试下载并保存一个 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)

这是我正在使用的代码:

货物.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(())
}

任何人都可以帮助我吗?

4

1 回答 1

5

reqwest::Response::text它将尝试解析您的请求正文并用替换字符替换任何无效的 UTF-8 序列。对于二进制文件,这将导致文件损坏。

相反,您需要使用reqwest::Response::byteswhich 按原样返回内容。

于 2020-07-11T16:15:04.833 回答