viz_core/types/
multipart.rs

1//! Represents a Multipart extractor.
2
3use form_data::FormData;
4
5use crate::{Body, Error, FromRequest, IntoResponse, Request, RequestExt, Response, StatusCode};
6
7use super::{Payload, PayloadError};
8
9pub use form_data::{Error as MultipartError, Limits as MultipartLimits};
10
11/// Extracts the data from the multipart body of a request.
12pub type Multipart<T = Body> = FormData<T>;
13
14impl<T> Payload for Multipart<T> {
15    const NAME: &'static str = "multipart";
16
17    // 2MB
18    const LIMIT: u64 = 1024 * 1024 * 2;
19
20    fn detect(m: &mime::Mime) -> bool {
21        m.type_() == mime::MULTIPART && m.subtype() == mime::FORM_DATA
22    }
23
24    fn mime() -> mime::Mime {
25        mime::MULTIPART_FORM_DATA
26    }
27}
28
29impl FromRequest for Multipart {
30    type Error = PayloadError;
31
32    #[inline]
33    async fn extract(req: &mut Request) -> Result<Self, Self::Error> {
34        req.multipart().await
35    }
36}
37
38impl IntoResponse for MultipartError {
39    fn into_response(self) -> Response {
40        (
41            match self {
42                Self::InvalidHeader
43                | Self::InvalidContentDisposition
44                | Self::FileTooLarge(_)
45                | Self::FieldTooLarge(_)
46                | Self::PartsTooMany(_)
47                | Self::FieldsTooMany(_)
48                | Self::FilesTooMany(_)
49                | Self::FieldNameTooLong(_) => StatusCode::BAD_REQUEST,
50                Self::PayloadTooLarge(_) => StatusCode::PAYLOAD_TOO_LARGE,
51                Self::Stream(_) | Self::BoxError(_) | Self::TryLockError(_) => {
52                    StatusCode::INTERNAL_SERVER_ERROR
53                }
54            },
55            self.to_string(),
56        )
57            .into_response()
58    }
59}
60
61impl From<MultipartError> for Error {
62    fn from(e: MultipartError) -> Self {
63        e.into_error()
64    }
65}