forked from abonander/multipart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnickel.rs
84 lines (71 loc) · 3 KB
/
nickel.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
extern crate multipart_nickel;
extern crate nickel;
use std::fs::File;
use std::io::Read;
use nickel::{HttpRouter, MiddlewareResult, Nickel, Request, Response};
use multipart_nickel::MultipartBody;
use multipart_nickel::multipart_server::{Entries, SaveResult};
fn handle_multipart<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> {
match req.multipart_body() {
Some(mut multipart) => {
match multipart.save().temp() {
SaveResult::Full(entries) => process_entries(res, entries),
SaveResult::Partial(entries, e) => {
println!("Partial errors ... {:?}", e);
return process_entries(res, entries.keep_partial());
},
SaveResult::Error(e) => {
println!("There are errors in multipart POSTing ... {:?}", e);
res.set(nickel::status::StatusCode::InternalServerError);
return res.send(format!("Server could not handle multipart POST! {:?}", e));
},
}
}
None => {
res.set(nickel::status::StatusCode::BadRequest);
return res.send("Request seems not was a multipart request")
}
}
}
/// Processes saved entries from multipart request.
/// Returns an OK response or an error.
fn process_entries<'mw>(res: Response<'mw>, entries: Entries) -> MiddlewareResult<'mw> {
for (name, field) in entries.fields {
println!("Field {:?}: {:?}", name, field);
}
for (name, files) in entries.files {
println!("Field {:?} has {} files:", name, files.len());
for saved_file in files {
match File::open(&saved_file.path) {
Ok(mut file) => {
let mut contents = String::new();
if let Err(e) = file.read_to_string(&mut contents) {
println!("Could not read file {:?}. Error: {:?}", saved_file.filename, e);
return res.error(nickel::status::StatusCode::BadRequest, "The uploaded file was not readable")
}
println!("File {:?} ({:?}):", saved_file.filename, saved_file.content_type);
println!("{}", contents);
file
}
Err(e) => {
println!("Could open file {:?}. Error: {:?}", saved_file.filename, e);
return res.error(nickel::status::StatusCode::BadRequest, "The uploaded file was not readable")
}
};
}
}
res.send("Ok")
}
fn main() {
let mut srv = Nickel::new();
srv.post("/multipart_upload/", handle_multipart);
// Start this example via:
//
// `cargo run --example nickel --features nickel`
//
// And - if you are in the root of this repository - do an example
// upload via:
//
// `curl -F file=@LICENSE 'http://localhost:6868/multipart_upload/'`
srv.listen("127.0.0.1:6868").expect("Failed to bind server");
}