How to get the content-length (or the entire header) of uploaded file on rocket?

Viewed 39

Here's a simplified version of the code:

#[post("/upload",data="<file>")]
fn upload_handler(file: Data) -> Redirect {
    let mut buffer = Vec::new();
    file.stream_to(&mut buffer).unwrap();
    println!("{}",String::from_utf8_lossy(&buffer));
    Redirect::to("/")
}

But all i get when reading the buffer is:

--------------------------f8761027cd2bdc69
Content-Disposition: form-data; name="file"; filename="teste.txt"
Content-Type: text/plain

CONTENT HERE

--------------------------f8761027cd2bdc69--

I want to be able to get the content length of the file without downloading it

1 Answers

After reading PitaJ's comment and a lot of searching i've done it. I think the rocket devs should make a better way of doing this, this seems kinda too much just to get the headers of a request.

struct RequestHeaders {
    host: String,
    user_agent: String,
    content_type: String,
    content_length: i32,
}

#[derive(Debug)]
enum RequestHeadersError {
    ShitHitTheFan,
}

impl<'a, 'r> FromRequest<'a, 'r> for RequestHeaders {
    type Error = RequestHeadersError;

    fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> {
        let mut headers = HashMap::new();
        for header in request.headers().iter() {
            headers.insert(header.name().to_owned(),header.value().to_owned());
        }
        let must_have = vec!["Host","User-Agent","Content-Type","Content-Length"];
        for item in must_have {
            if !headers.contains_key(item){
                return Outcome::Failure((Status::BadRequest,RequestHeadersError::ShitHitTheFan));
            }
        }
        let return_headers = RequestHeaders {
            host: headers.get("Host").unwrap().to_owned(),
            user_agent: headers.get("User-Agent").unwrap().to_owned(),
            content_type: headers.get("Content-Type").unwrap().to_owned(),
            content_length: headers.get("Content-Length").unwrap().parse::<i32>().unwrap()
        };
        return Outcome::Success(return_headers)
    }
}

#[post("/upload",data="<file_data>")]
fn upload_handler(headers: RequestHeaders,file_data: Data) -> Result<Template,Status> {
    if headers.content_length > UPLOAD_LIMIT as i32 {
        return Err(Status::PayloadTooLarge)
    }
    todo()...
}
Related