1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-25 00:12:59 +01:00
actix-extras/examples/multipart/src/main.rs

82 lines
2.4 KiB
Rust
Raw Normal View History

2017-10-20 01:22:21 +02:00
#![allow(unused_variables)]
2017-10-19 08:43:50 +02:00
extern crate actix;
extern crate actix_web;
extern crate env_logger;
use actix::*;
use actix_web::*;
struct MyRoute;
impl Actor for MyRoute {
type Context = HttpContext<Self>;
}
impl Route for MyRoute {
type State = ();
fn request(req: HttpRequest, payload: Payload, ctx: &mut HttpContext<Self>) -> Reply<Self> {
println!("{:?}", req);
2017-10-22 00:21:16 +02:00
let multipart = match req.multipart(payload) {
Ok(mp) => mp,
Err(e) => return Reply::reply(e),
};
2017-10-20 01:22:21 +02:00
// get Multipart stream
2017-10-22 00:21:16 +02:00
WrapStream::<MyRoute>::actstream(multipart)
2017-10-20 01:22:21 +02:00
.and_then(|item, act, ctx| {
2017-10-21 02:16:17 +02:00
// Multipart stream is a stream of Fields and nested Multiparts
2017-10-20 01:22:21 +02:00
match item {
multipart::MultipartItem::Field(field) => {
println!("==== FIELD ==== {:?}", field);
2017-10-19 08:43:50 +02:00
2017-10-20 01:22:21 +02:00
// Read field's stream
fut::Either::A(
field.actstream()
.map(|chunk, act, ctx| {
println!(
"-- CHUNK: \n{}",
std::str::from_utf8(&chunk.0).unwrap());
})
.finish())
},
multipart::MultipartItem::Nested(mp) => {
// Do nothing for nested multipart stream
fut::Either::B(fut::ok(()))
}
}
})
// wait until stream finish
.finish()
.map_err(|e, act, ctx| {
ctx.start(httpcodes::HTTPBadRequest);
ctx.write_eof();
})
.map(|_, act, ctx| {
ctx.start(httpcodes::HTTPOk);
ctx.write_eof();
})
.spawn(ctx);
2017-10-19 08:43:50 +02:00
2017-10-20 01:22:21 +02:00
Reply::async(MyRoute)
2017-10-19 08:43:50 +02:00
}
}
fn main() {
let _ = env_logger::init();
let sys = actix::System::new("multipart-example");
HttpServer::new(
RoutingMap::default()
.app("/", Application::default()
.resource("/multipart", |r| {
r.post::<MyRoute>();
})
.finish())
.finish())
.serve::<_, ()>("127.0.0.1:8080").unwrap();
let _ = sys.run();
}