How to parse multipart forms using abonander / multipart with Rocket?

This might be helpful for me :

I have no idea how you are going to parse a multipart form other than doing it manually using only the raw data line after input

I'll try to customize the Hyper example , but any help would be much appreciated.

Topical issues:

+5


source to share


2 answers


The primary abstraction of the data rocket is the trait FromData

. Given the POST data and the request, you can create this type:

pub trait FromData: Sized {
    type Error;
    fn from_data(request: &Request, data: Data) -> Outcome<Self, Self::Error>;
}

      

Then you just need to read the API for multiple parts and insert tab A into slot B:

#![feature(plugin)]
#![plugin(rocket_codegen)]

extern crate rocket;
extern crate multipart;

#[post("/", data = "<upload>")]
fn index(upload: DummyMultipart) -> String {
    format!("I read this: {:?}", upload)
}

#[derive(Debug)]
struct DummyMultipart {
    alpha: String,
    one: i32,
    file: Vec<u8>,
}

use std::io::{Cursor, Read};
use rocket::{Request, Data, Outcome};
use rocket::data::{self, FromData};
use multipart::server::Multipart;

impl FromData for DummyMultipart {
    type Error = ();

    fn from_data(request: &Request, data: Data) -> data::Outcome<Self, Self::Error> {
        // All of these errors should be reported
        let ct = request.headers().get_one("Content-Type").expect("no content-type");
        let idx = ct.find("boundary=").expect("no boundary");
        let boundary = &ct[(idx + "boundary=".len())..];

        let mut d = Vec::new();
        data.stream_to(&mut d).expect("Unable to read");

        let mut mp = Multipart::with_body(Cursor::new(d), boundary);

        // Custom implementation parts

        let mut alpha = None;
        let mut one = None;
        let mut file = None;

        mp.foreach_entry(|mut entry| {
            match entry.name.as_str() {
                "alpha" => {
                    let t = entry.data.as_text().expect("not text");
                    alpha = Some(t.into());
                },
                "one" => {
                    let t = entry.data.as_text().expect("not text");
                    let n = t.parse().expect("not number");
                    one = Some(n);
                },
                "file" => {
                    let mut d = Vec::new();
                    let f = entry.data.as_file().expect("not file");
                    f.read_to_end(&mut d).expect("cant read");
                    file = Some(d);
                },
                other => panic!("No known key {}", other),
            }
        }).expect("Unable to iterate");

        let v = DummyMultipart {
            alpha: alpha.expect("alpha not set"),
            one: one.expect("one not set"),
            file: file.expect("file not set"),
        };

        // End custom

        Outcome::Success(v)
    }
}

fn main() {
    rocket::ignite().mount("/", routes![index]).launch();
}

      

I've never used any of these APIs about an hour ago, so there is no guarantee that this is a good implementation. In fact, any panic about a bug definitely means that it is sub-optimal. Production use will handle it all cleanly.



However, this works:

$ curl -X POST -F alpha=omega -F one=2 -F file=@hello http://localhost:8000/
I read this: DummyMultipart { alpha: "omega", one: 2, file: [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 10] }

      


The improved implementation allows some abstraction between user data and common multipart aspects. It would be nice to have something like Multipart<MyForm>

.

The author of Rocket points out that this solution allows a malicious end user to put in a POST file of infinite size, which will exhaust the computer's memory. Depending on the intended use, you can set a limit on the number of bytes read, which can result in a write to the filesystem at some breakpoint.

+8


source


Official support for multiparticle analysis in Rocket is still under discussion . Until then, take a look at the official example of Rocket's multipurpose box integration: https://github.com/abonander/multipart/blob/master/examples/rocket.rs



0


source







All Articles