我需要下载一个 60MB 的 ZIP 文件并提取其中的唯一文件。我想下载它并使用流提取它。我如何使用 Rust 实现这一点?
fn main () {
let mut res = reqwest::get("myfile.zip").unwrap();
// extract the response body to myfile.txt
}
在 Node.js 中我会做这样的事情:
http.get('myfile.zip', response => {
response.pipe(unzip.Parse())
.on('entry', entry => {
if (entry.path.endsWith('.txt')) {
entry.pipe(fs.createWriteStream('myfile.txt'))
}
})
})
最佳答案
与 reqwest
你可以得到 .zip
文件:
reqwest::get("myfile.zip")
由于reqwest
只能用于检索文件,ZipArchive
来自 zip
crate 可用于拆包。无法将 .zip
文件流式传输到 ZipArchive
,因为 ZipArchive::new(reader: R)
需要 R
来实现 Read
(由 reqwest
的 Response
实现)和 Seek
,它不是由 Response
实现的。
作为解决方法,您可以使用临时文件:
copy_to(&mut tmpfile)
作为File
实现Seek
和Read
,zip
可以在这里使用:
zip::ZipArchive::new(tmpfile)
这是所描述方法的一个工作示例:
extern crate reqwest;
extern crate tempfile;
extern crate zip;
use std::io::Read;
fn main() {
let mut tmpfile = tempfile::tempfile().unwrap();
reqwest::get("myfile.zip").unwrap().copy_to(&mut tmpfile);
let mut zip = zip::ZipArchive::new(tmpfile).unwrap();
println!("{:#?}", zip);
}
tempfile
是一个方便的 crate,它可以让你创建一个临时文件,所以你不必想一个名字。
关于rust - 如何使用流解压缩 Reqwest/Hyper 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50471218/