|
| 1 | +use crate::error::Error; |
| 2 | +use crate::extract::{FromRequest, PathParams}; |
| 3 | +use crate::state::AppState; |
| 4 | +use futures_util::stream::StreamExt; |
| 5 | +use http::header::CONTENT_TYPE; |
| 6 | +use hyper::body::Incoming; |
| 7 | +use std::io; |
| 8 | +use std::sync::Arc; |
| 9 | + |
| 10 | +/// Extractor for multipart form data. |
| 11 | +/// |
| 12 | +/// This extractor provides access to the individual fields of a multipart request. |
| 13 | +/// It uses `multer` under the hood for efficient streaming. |
| 14 | +/// |
| 15 | +/// # Examples |
| 16 | +/// |
| 17 | +/// ```rust,ignore |
| 18 | +/// use rapina::prelude::*; |
| 19 | +/// |
| 20 | +/// #[post("/upload")] |
| 21 | +/// async fn upload(mut multipart: Multipart) -> Result<String> { |
| 22 | +/// while let Some(mut field) = multipart.next_field().await? { |
| 23 | +/// let name = field.name().unwrap_or("unknown").to_string(); |
| 24 | +/// let file_name = field.file_name().map(|s| s.to_string()); |
| 25 | +/// |
| 26 | +/// if let Some(file_name) = file_name { |
| 27 | +/// println!("Uploading file: {} as field: {}", file_name, name); |
| 28 | +/// let data = field.bytes().await?; |
| 29 | +/// // Process file data... |
| 30 | +/// } else { |
| 31 | +/// let text = field.text().await?; |
| 32 | +/// println!("Field: {} = {}", name, text); |
| 33 | +/// } |
| 34 | +/// } |
| 35 | +/// Ok("Upload successful".to_string()) |
| 36 | +/// } |
| 37 | +/// ``` |
| 38 | +pub struct Multipart { |
| 39 | + inner: multer::Multipart<'static>, |
| 40 | +} |
| 41 | + |
| 42 | +impl FromRequest for Multipart { |
| 43 | + async fn from_request( |
| 44 | + req: http::Request<Incoming>, |
| 45 | + _params: &PathParams, |
| 46 | + _state: &Arc<AppState>, |
| 47 | + ) -> Result<Self, Error> { |
| 48 | + let boundary = req |
| 49 | + .headers() |
| 50 | + .get(CONTENT_TYPE) |
| 51 | + .and_then(|v| v.to_str().ok()) |
| 52 | + .and_then(|v| multer::parse_boundary(v).ok()) |
| 53 | + .ok_or_else(|| Error::bad_request("invalid or missing multipart boundary"))?; |
| 54 | + |
| 55 | + let stream = |
| 56 | + http_body_util::BodyStream::new(req.into_body()).filter_map(|result| async move { |
| 57 | + match result { |
| 58 | + Ok(frame) => frame.into_data().ok().map(Ok::<_, multer::Error>), |
| 59 | + Err(e) => Some(Err(multer::Error::StreamReadFailed(Box::new( |
| 60 | + io::Error::other(e), |
| 61 | + )))), |
| 62 | + } |
| 63 | + }); |
| 64 | + |
| 65 | + Ok(Self::new_with_stream(stream, boundary)) |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +impl Multipart { |
| 70 | + /// Creates a new `Multipart` instance from a stream and boundary. |
| 71 | + pub(crate) fn new_with_stream<S>(stream: S, boundary: impl Into<String>) -> Self |
| 72 | + where |
| 73 | + S: futures_util::Stream<Item = Result<bytes::Bytes, multer::Error>> + Send + 'static, |
| 74 | + { |
| 75 | + let multipart = multer::Multipart::new(stream, boundary); |
| 76 | + Multipart { inner: multipart } |
| 77 | + } |
| 78 | + |
| 79 | + /// Yields the next field from the multipart body. |
| 80 | + /// |
| 81 | + /// Returns `Ok(Some(field))` if a field is available, `Ok(None)` if the end of |
| 82 | + /// the stream is reached, or an error if the request is malformed. |
| 83 | + pub async fn next_field(&mut self) -> Result<Option<Field<'static>>, Error> { |
| 84 | + match self.inner.next_field().await { |
| 85 | + Ok(Some(inner)) => Ok(Some(Field { inner })), |
| 86 | + Ok(None) => Ok(None), |
| 87 | + Err(e) => Err(Error::bad_request(format!("multipart error: {}", e))), |
| 88 | + } |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +/// A single field in a multipart body. |
| 93 | +/// |
| 94 | +/// Provides methods to access field metadata and stream its contents. |
| 95 | +pub struct Field<'a> { |
| 96 | + inner: multer::Field<'a>, |
| 97 | +} |
| 98 | + |
| 99 | +impl<'a> Field<'a> { |
| 100 | + /// Returns the name of the field from the `Content-Disposition` header. |
| 101 | + pub fn name(&self) -> Option<&str> { |
| 102 | + self.inner.name() |
| 103 | + } |
| 104 | + |
| 105 | + /// Returns the filename of the field from the `Content-Disposition` header. |
| 106 | + pub fn file_name(&self) -> Option<&str> { |
| 107 | + self.inner.file_name() |
| 108 | + } |
| 109 | + |
| 110 | + /// Returns the content type of the field from the `Content-Type` header. |
| 111 | + pub fn content_type(&self) -> Option<&str> { |
| 112 | + self.inner.content_type().map(|c| c.as_ref()) |
| 113 | + } |
| 114 | + |
| 115 | + /// Reads the next chunk of bytes from the field. |
| 116 | + /// |
| 117 | + /// Useful for streaming large files without loading the entire content into memory. |
| 118 | + pub async fn chunk(&mut self) -> Result<Option<bytes::Bytes>, Error> { |
| 119 | + self.inner |
| 120 | + .chunk() |
| 121 | + .await |
| 122 | + .map_err(|e| Error::bad_request(format!("multipart field error: {}", e))) |
| 123 | + } |
| 124 | + |
| 125 | + /// Collects the remaining bytes from the field into a `Bytes`. |
| 126 | + pub async fn bytes(self) -> Result<bytes::Bytes, Error> { |
| 127 | + self.inner |
| 128 | + .bytes() |
| 129 | + .await |
| 130 | + .map_err(|e| Error::bad_request(format!("multipart field error: {}", e))) |
| 131 | + } |
| 132 | + |
| 133 | + /// Collects the remaining bytes from the field into a `String`. |
| 134 | + pub async fn text(self) -> Result<String, Error> { |
| 135 | + self.inner |
| 136 | + .text() |
| 137 | + .await |
| 138 | + .map_err(|e| Error::bad_request(format!("multipart field error: {}", e))) |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +#[cfg(test)] |
| 143 | +mod tests { |
| 144 | + use super::*; |
| 145 | + use bytes::Bytes; |
| 146 | + use futures_util::stream; |
| 147 | + |
| 148 | + #[tokio::test] |
| 149 | + async fn test_multipart_extraction() { |
| 150 | + let boundary = "boundary"; |
| 151 | + let body = format!( |
| 152 | + "--{boundary}\r\n\ |
| 153 | + Content-Disposition: form-data; name=\"foo\"\r\n\ |
| 154 | + \r\n\ |
| 155 | + bar\r\n\ |
| 156 | + --{boundary}--\r\n" |
| 157 | + ); |
| 158 | + |
| 159 | + let stream = stream::once(async move { Ok::<_, multer::Error>(Bytes::from(body)) }); |
| 160 | + let mut multipart = Multipart::new_with_stream(stream, boundary); |
| 161 | + |
| 162 | + let field = multipart.next_field().await.unwrap().unwrap(); |
| 163 | + assert_eq!(field.name(), Some("foo")); |
| 164 | + assert_eq!(field.text().await.unwrap(), "bar"); |
| 165 | + |
| 166 | + assert!(multipart.next_field().await.unwrap().is_none()); |
| 167 | + } |
| 168 | + |
| 169 | + #[tokio::test] |
| 170 | + async fn test_multipart_multiple_fields() { |
| 171 | + let boundary = "boundary"; |
| 172 | + let body = format!( |
| 173 | + "--{boundary}\r\n\ |
| 174 | + Content-Disposition: form-data; name=\"foo\"\r\n\ |
| 175 | + \r\n\ |
| 176 | + bar\r\n\ |
| 177 | + --{boundary}\r\n\ |
| 178 | + Content-Disposition: form-data; name=\"baz\"; filename=\"test.txt\"\r\n\ |
| 179 | + Content-Type: text/plain\r\n\ |
| 180 | + \r\n\ |
| 181 | + qux\r\n\ |
| 182 | + --{boundary}--\r\n" |
| 183 | + ); |
| 184 | + |
| 185 | + let stream = stream::once(async move { Ok::<_, multer::Error>(Bytes::from(body)) }); |
| 186 | + let mut multipart = Multipart::new_with_stream(stream, boundary); |
| 187 | + |
| 188 | + let field1 = multipart.next_field().await.unwrap().unwrap(); |
| 189 | + assert_eq!(field1.name(), Some("foo")); |
| 190 | + assert_eq!(field1.text().await.unwrap(), "bar"); |
| 191 | + |
| 192 | + let field2 = multipart.next_field().await.unwrap().unwrap(); |
| 193 | + assert_eq!(field2.name(), Some("baz")); |
| 194 | + assert_eq!(field2.file_name(), Some("test.txt")); |
| 195 | + assert_eq!(field2.content_type(), Some("text/plain")); |
| 196 | + assert_eq!(field2.text().await.unwrap(), "qux"); |
| 197 | + |
| 198 | + assert!(multipart.next_field().await.unwrap().is_none()); |
| 199 | + } |
| 200 | +} |
0 commit comments