Skip to content

Commit e021321

Browse files
add example to use Easy2 in downloading files
1 parent de57280 commit e021321

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

examples/file_download.rs

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/// This is an example how to use Easy2 to download a file.
2+
/// Can able to resume a download and control download speed.
3+
use std::{fs::OpenOptions, io::Write, path::PathBuf};
4+
5+
use curl::easy::{Easy2, Handler, WriteError};
6+
7+
enum Collector {
8+
File(PathBuf),
9+
// You can add what type of storage you want
10+
}
11+
12+
impl Handler for Collector {
13+
fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> {
14+
match self {
15+
Collector::File(download_path) => {
16+
println!("File chunk size: {}", data.len());
17+
let mut file = OpenOptions::new()
18+
.create(true)
19+
.append(true)
20+
.open(download_path)
21+
.map_err(|e| {
22+
eprintln!("{}", e);
23+
WriteError::Pause
24+
})?;
25+
26+
file.write_all(data).map_err(|e| {
27+
eprintln!("{}", e);
28+
WriteError::Pause
29+
})?;
30+
Ok(data.len())
31+
}
32+
}
33+
}
34+
}
35+
fn main() {
36+
let collector = Collector::File(PathBuf::from("<Your target path>"));
37+
let mut easy2 = Easy2::new(collector);
38+
39+
easy2.url("https://www.rust-lang.org/").unwrap();
40+
easy2.get(true).unwrap();
41+
// Setting of download speed control in bytes per second
42+
easy2.max_recv_speed(2000).unwrap();
43+
// Can resume download by giving a byte offset
44+
easy2.resume_from(0).unwrap();
45+
easy2.perform().unwrap();
46+
47+
let status_code = easy2.response_code().unwrap();
48+
let content_type = easy2.content_type().unwrap();
49+
eprintln!("Content Type: {:?}", content_type);
50+
eprintln!("Status Code: {}", status_code);
51+
}

0 commit comments

Comments
 (0)