1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-06-25 09:59:21 +02:00

update multipart impl

This commit is contained in:
Nikolay Kim
2017-10-19 16:22:21 -07:00
parent aaef550bc5
commit 24804250a8
8 changed files with 353 additions and 143 deletions

View File

@ -9,5 +9,6 @@ path = "src/main.rs"
[dependencies]
env_logger = "*"
actix = "0.2"
# actix = "0.2"
actix = { git = "https://github.com/fafhrd91/actix.git" }
actix-web = { path = "../../" }

View File

@ -2,7 +2,7 @@ import asyncio
import aiohttp
def client():
def req1():
with aiohttp.MultipartWriter() as writer:
writer.append('test')
writer.append_json({'passed': True})
@ -14,5 +14,19 @@ def client():
assert 200 == resp.status
def req2():
with aiohttp.MultipartWriter() as writer:
writer.append('test')
writer.append_json({'passed': True})
writer.append(open('src/main.rs'))
resp = yield from aiohttp.request(
"post", 'http://localhost:8080/multipart',
data=writer, headers=writer.headers)
print(resp)
assert 200 == resp.status
loop = asyncio.get_event_loop()
loop.run_until_complete(client())
loop.run_until_complete(req1())
loop.run_until_complete(req2())

View File

@ -1,3 +1,4 @@
#![allow(unused_variables)]
extern crate actix;
extern crate actix_web;
extern crate env_logger;
@ -16,39 +17,44 @@ impl Route for MyRoute {
fn request(req: HttpRequest, payload: Payload, ctx: &mut HttpContext<Self>) -> Reply<Self> {
println!("{:?}", req);
match req.multipart(payload) {
Ok(multipart) => {
ctx.add_stream(multipart);
Reply::async(MyRoute)
},
// can not read multipart
Err(_) => {
Reply::reply(httpcodes::HTTPBadRequest)
}
}
}
}
impl ResponseType<multipart::MultipartItem> for MyRoute {
type Item = ();
type Error = ();
}
// get Multipart stream
WrapStream::<MyRoute>::actstream(req.multipart(payload)?)
.and_then(|item, act, ctx| {
// Multipart stream is a string of Fields and nested Multiparts
match item {
multipart::MultipartItem::Field(field) => {
println!("==== FIELD ==== {:?}", field);
impl StreamHandler<multipart::MultipartItem, PayloadError> for MyRoute {
fn finished(&mut self, ctx: &mut Self::Context) {
println!("FINISHED");
ctx.start(httpcodes::HTTPOk);
ctx.write_eof();
}
}
// 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);
impl Handler<multipart::MultipartItem, PayloadError> for MyRoute {
fn handle(&mut self, msg: multipart::MultipartItem, ctx: &mut HttpContext<Self>)
-> Response<Self, multipart::MultipartItem>
{
println!("==== FIELD ==== {:?}", msg);
//if let Some(req) = self.req.take() {
Self::empty()
Reply::async(MyRoute)
}
}