1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
use std::{
io::{Error as IoError, ErrorKind},
str::FromStr,
};
use futures_util::TryStreamExt;
use mime::Mime;
#[cfg(feature = "tempfile")]
use tokio::fs::File;
use tokio::io::{AsyncRead, AsyncReadExt};
#[cfg(feature = "tempfile")]
use tokio::io::{AsyncSeekExt, SeekFrom};
use crate::{error::ParseMultipartError, http::header, FromRequest, Request, RequestBody, Result};
#[cfg_attr(docsrs, doc(cfg(feature = "multipart")))]
pub struct Field(multer::Field<'static>);
impl Field {
#[inline]
pub fn content_type(&self) -> Option<&str> {
self.0.content_type().map(|mime| mime.essence_str())
}
#[inline]
pub fn file_name(&self) -> Option<&str> {
self.0.file_name()
}
#[inline]
pub fn name(&self) -> Option<&str> {
self.0.name()
}
pub async fn bytes(self) -> Result<Vec<u8>, IoError> {
let mut data = Vec::new();
let mut buf = [0; 2048];
let mut reader = self.into_async_read();
loop {
let sz = reader.read(&mut buf[..]).await?;
if sz > 0 {
data.extend_from_slice(&buf[..sz]);
} else {
break;
}
}
Ok(data)
}
#[inline]
pub async fn text(self) -> Result<String, IoError> {
String::from_utf8(self.bytes().await?).map_err(|err| IoError::new(ErrorKind::Other, err))
}
#[cfg(feature = "tempfile")]
#[cfg_attr(docsrs, doc(cfg(feature = "tempfile")))]
pub async fn tempfile(self) -> Result<File, IoError> {
let mut reader = self.into_async_read();
let mut file = tokio::fs::File::from_std(::libtempfile::tempfile()?);
tokio::io::copy(&mut reader, &mut file).await?;
file.seek(SeekFrom::Start(0)).await?;
Ok(file)
}
pub fn into_async_read(self) -> impl AsyncRead + Send {
tokio_util::io::StreamReader::new(
self.0
.map_err(|err| std::io::Error::new(ErrorKind::Other, err.to_string())),
)
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "multipart")))]
pub struct Multipart {
inner: multer::Multipart<'static>,
}
#[async_trait::async_trait]
impl<'a> FromRequest<'a> for Multipart {
type Error = ParseMultipartError;
async fn from_request(req: &'a Request, body: &mut RequestBody) -> Result<Self, Self::Error> {
let content_type = req
.headers()
.get(header::CONTENT_TYPE)
.and_then(|err| err.to_str().ok())
.and_then(|value| Mime::from_str(value).ok())
.ok_or(ParseMultipartError::ContentTypeRequired)?;
if content_type.essence_str() != mime::MULTIPART_FORM_DATA {
return Err(ParseMultipartError::InvalidContentType(
content_type.essence_str().to_string(),
));
}
let boundary = multer::parse_boundary(content_type.as_ref())?;
Ok(Self {
inner: multer::Multipart::new(
tokio_util::io::ReaderStream::new(body.take()?.into_async_read()),
boundary,
),
})
}
}
impl Multipart {
pub async fn next_field(&mut self) -> Result<Option<Field>, ParseMultipartError> {
match self.inner.next_field().await? {
Some(field) => Ok(Some(Field(field))),
None => Ok(None),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{handler, http::StatusCode, Endpoint};
#[tokio::test]
async fn test_multipart_extractor_content_type() {
#[handler(internal)]
async fn index(_multipart: Multipart) {
todo!()
}
let mut resp = index
.call(
Request::builder()
.header("content-type", "multipart/json; boundary=X-BOUNDARY")
.body(()),
)
.await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
assert_eq!(
resp.take_body().into_string().await.unwrap(),
"invalid content type `multipart/json`, expect: `multipart/form-data`"
);
}
#[tokio::test]
async fn test_multipart_extractor() {
#[handler(internal)]
async fn index(mut multipart: Multipart) {
let field = multipart.next_field().await.unwrap().unwrap();
assert_eq!(field.name(), Some("my_text_field"));
assert_eq!(field.text().await.unwrap(), "abcd");
let field = multipart.next_field().await.unwrap().unwrap();
assert_eq!(field.name(), Some("my_file_field"));
assert_eq!(field.file_name(), Some("a-text-file.txt"));
assert_eq!(field.content_type(), Some("text/plain"));
assert_eq!(
field.text().await.unwrap(),
"Hello world\nHello\r\nWorld\rAgain"
);
}
let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_file_field\"; filename=\"a-text-file.txt\"\r\nContent-Type: text/plain\r\n\r\nHello world\nHello\r\nWorld\rAgain\r\n--X-BOUNDARY--\r\n";
let resp = index
.call(
Request::builder()
.header("content-type", "multipart/form-data; boundary=X-BOUNDARY")
.body(data),
)
.await;
assert_eq!(resp.status(), StatusCode::OK);
}
}