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
use http::header;
use multer::{Field, Multipart};
use multimap::MultiMap;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use tempdir::TempDir;
use textnonce::TextNonce;
use tokio::{fs::File, io::AsyncWriteExt};
use crate::http::errors::ReadError;
use crate::http::header::HeaderMap;
use crate::http::request::{self, Body};
pub struct FormData {
pub fields: MultiMap<String, String>,
pub files: MultiMap<String, FilePart>,
}
impl FormData {
pub fn new() -> FormData {
FormData {
fields: MultiMap::new(),
files: MultiMap::new(),
}
}
}
impl Default for FormData {
fn default() -> Self {
FormData {
fields: MultiMap::new(),
files: MultiMap::new(),
}
}
}
fn get_extension_from_filename(filename: &str) -> Option<&str> {
Path::new(filename).extension().and_then(OsStr::to_str)
}
#[derive(Debug)]
pub struct FilePart {
pub file_name: Option<String>,
pub headers: HeaderMap,
pub path: PathBuf,
pub size: Option<usize>,
temp_dir: Option<PathBuf>,
}
impl FilePart {
pub fn do_not_delete_on_drop(&mut self) {
self.temp_dir = None;
}
pub async fn create(field: &mut Field<'_>) -> Result<FilePart, ReadError> {
let mut path = tokio::task::spawn_blocking(|| TempDir::new("salvo_http_multipart"))
.await
.expect("Runtime spawn blocking poll error")?
.into_path();
let temp_dir = Some(path.clone());
let file_name = field.file_name().map(|s| s.to_owned());
path.push(format!(
"{}.{}",
TextNonce::sized_urlsafe(32).unwrap().into_string(),
file_name
.as_deref()
.and_then(|f| get_extension_from_filename(&f))
.unwrap_or("unknown")
));
let mut file = File::create(&path).await?;
while let Some(chunk) = field.chunk().await? {
file.write_all(&chunk).await?;
}
Ok(FilePart {
file_name,
headers: field.headers().to_owned(),
path,
size: None,
temp_dir,
})
}
pub fn file_name(&self) -> Option<&str> {
self.file_name.as_deref()
}
}
impl Drop for FilePart {
fn drop(&mut self) {
if self.temp_dir.is_some() {
let path = self.path.clone();
let temp_dir = self.temp_dir.clone();
tokio::task::spawn_blocking(move || {
let _ = ::std::fs::remove_file(&path);
let _ = ::std::fs::remove_dir(temp_dir.as_ref().unwrap());
});
}
}
}
pub async fn read_form_data(headers: &HeaderMap, body: Body) -> Result<FormData, ReadError> {
match headers.get(header::CONTENT_TYPE) {
Some(ctype) if ctype == "application/x-www-form-urlencoded" => {
let data = request::read_body_bytes(body).await?;
let mut form_data = FormData::new();
form_data.fields = form_urlencoded::parse(data.as_ref()).into_owned().collect();
Ok(form_data)
}
Some(ctype) if ctype.to_str().unwrap_or("").starts_with("multipart/form-data") => {
let mut form_data = FormData::new();
if let Some(boundary) = headers
.get(header::CONTENT_TYPE)
.and_then(|ct| ct.to_str().ok())
.and_then(|ct| multer::parse_boundary(ct).ok())
{
let mut multipart = Multipart::new(body, boundary);
while let Some(mut field) = multipart.next_field().await? {
if let Some(name) = field.name().map(|s| s.to_owned()) {
if let Some(content_type) = field.headers().get(header::CONTENT_TYPE) {
if content_type.to_str().unwrap_or_default().starts_with("text/") {
form_data.fields.insert(name, field.text().await?);
} else {
form_data.files.insert(name, FilePart::create(&mut field).await?);
}
}
}
}
}
Ok(form_data)
}
_ => Err(ReadError::Parsing("parse form data failed".into())),
}
}