我正在使用 ftp crate从 FTP 服务器下载文件:
extern crate ftp;
extern crate chrono;
use std::env;
use std::fs::File;
use std::str;
use std::io::{Result, Write};
use ftp::FtpStream;
use chrono::*;
fn main() {
let args: Vec<String> = env::args().collect();
ftpgp(&args[1], &args[2], &args[3], &args[4]).unwrap_or_else(|err|
panic!("{}", err)
);
}
fn ftpgp(addr: &str, user: &str, pass: &str, remote_path: &str,) -> Result<()> {
let dt = Local::now();
let now = dt.format("%Y-%m-%d %H:%M:%S").to_string();
let mut ftp_stream = try!(FtpStream::connect((addr, 21)));
try!(ftp_stream.login(user, pass));
ftp_stream.cwd(remote_path).unwrap();
let file_list = try!(ftp_stream.nlst(None));
let files: Vec<String> = file_list.into_iter()
.filter(|name| name.ends_with(".zip"))
.collect();
for file in files {
try!(ftp_stream.retr(file.as_str(), |stream| {
let mut file = File::create(file.clone()).unwrap();
let mut buf = [0; 2048];
loop {
match stream.read(&mut buf) {
Ok(0) => break,
Ok(n) => file.write_all(&buf[0..n]).unwrap(),
Err(err) => return Err(err)
};
}
Ok(())
}));
println!("{} Saving: {}", now, file);
ftp_stream.rm(file.as_str()).unwrap();
println!("{} Delete from ftp: {}", now, file);
}
ftp_stream.quit()
}
但下载后 zip 文件已损坏:
unzip -t sample.zip
Archive: sample.zip
warning [sample.zip]: 252314 extra bytes at beginning or within zipfile
(attempting to process anyway)
file #1: bad zipfile offset (local header sig): 252314
(attempting to re-compensate)
testing: sample.pdf
error: invalid compressed data to inflate
file #2: bad zipfile offset (local header sig): 67841095
(attempting to re-compensate)
file #2: bad zipfile offset (local header sig): 67841095
file #3: bad zipfile offset (local header sig): 68093906
我已经设置了要传输的文件类型,但我不知道如何。
像这样:
ftp_stream.transfer_type(Binary);
不管用。
error: unresolved name `Binary`