How to use multipart/form-data with hyper server and multer in Rust?

162 views Asked by At

Currently I am trying to make file uploads to my web server - built on top of hyper - work. For that a request with multipart/form-data is sent to it.

Since hyper is using struct Incoming on the 1.0.0-rc.4 version and multer::Multipart is requiring the stream to implement the trait futures_core::stream::Stream I am unable to make this work. If I understand it correctly, somehow I need to implement a wrapper struct but since the poll_frame method of Incoming is private, I am not able to call it from outside.

So yea, I am out of ideas and hope you can help me with that.

Code trying to use Multipart:

pub async fn handle_request(
    &self,
    mut req: Request,
) -> Result<hyper::Response<Full<Bytes>>, Infallible> {
    // req.collect_body().await; // * The way I use it for normal API requests

    let stream = req.body_stream_mut();
    let mut multipart = Multipart::new(stream, "EvaluatedBoundary"); // <-- The important part that causes the error "the trait bound `hyper::body::Incoming: futures_core::stream::Stream` is not satisfied ..."

    let mut res = view_function(&req).await; // * Maybe I change this to &mut so that the view_function can decide if it want to collect the body or use the stream in another way like Multipart

    res
}

Code of my Request implementation:

impl Request {
    pub fn from(hyper_req: hyper::Request<hyper::body::Incoming>) -> Self {
        let (req, body) = hyper_req.into_parts();
        Request {
            body: Bytes::new(),
            body_stream: body,
            uri: req.uri,
        }
    }

    pub async fn collect_body(&mut self) -> &hyper::body::Bytes {
        let collected_body = self
            .body_stream_mut()
            .collect()
            .await
            .ok()
            .unwrap_or_default()
            .to_bytes();

        self.body = collected_body;

        &self.body
    }

    pub fn body_stream_mut(&mut self) -> &mut hyper::body::Incoming {
        &mut self.body_stream
    }
}
0

There are 0 answers