|
| 1 | +//! Multipart support. |
| 2 | +
|
| 3 | +use mime_guess::Mime; |
| 4 | +use ureq_proto::http; |
| 5 | + |
| 6 | +use crate::{util::private::Private, AsSendBody, SendBody}; |
| 7 | +use std::io::{self, Read}; |
| 8 | +use std::path::Path; |
| 9 | + |
| 10 | +const BOUNDARY_PREFIX: &str = "----formdata-ureq-"; |
| 11 | +const BOUNDARY_SUFFIX_LEN: usize = 16; |
| 12 | + |
| 13 | +/// A multipart/form-data request. |
| 14 | +/// |
| 15 | +/// Use this to send multipart form data, which is commonly used for file uploads |
| 16 | +/// and forms with mixed content types. |
| 17 | +/// |
| 18 | +/// # Examples |
| 19 | +/// |
| 20 | +/// Basic usage with file upload: |
| 21 | +/// |
| 22 | +/// ``` |
| 23 | +/// # async fn no_run() -> Result<(), ureq::Error> { |
| 24 | +/// use ureq::multipart::Form; |
| 25 | +/// |
| 26 | +/// let form = Form::new() |
| 27 | +/// .text("description", "My uploaded file") |
| 28 | +/// .file("upload", "path/to/file.txt").await?; |
| 29 | +/// |
| 30 | +/// // Send the form as part of a POST request |
| 31 | +/// let response = ureq::post("http://httpbin.org/post") |
| 32 | +/// .send(form)?; |
| 33 | +/// # Ok(())} |
| 34 | +/// ``` |
| 35 | +/// |
| 36 | +/// Adding different types of parts: |
| 37 | +/// |
| 38 | +/// ``` |
| 39 | +/// # fn no_run() -> Result<(), ureq::Error> { |
| 40 | +/// use ureq::multipart::{Form, Part}; |
| 41 | +/// |
| 42 | +/// let data = b"binary data"; |
| 43 | +/// let form = Form::new() |
| 44 | +/// .text("field1", "text value") |
| 45 | +/// .part("field2", Part::bytes(data)) |
| 46 | +/// .part("field3", Part::text("another text").file_name("data.txt")); |
| 47 | +/// |
| 48 | +/// let response = ureq::post("http://httpbin.org/post") |
| 49 | +/// .send(form)?; |
| 50 | +/// # Ok(())} |
| 51 | +/// ``` |
| 52 | +pub struct Form<'a> { |
| 53 | + parts: Vec<(&'a str, Part<'a>)>, |
| 54 | + boundary: String, |
| 55 | + state: ReadState, |
| 56 | +} |
| 57 | + |
| 58 | +/// A field in a multipart form. |
| 59 | +pub struct Part<'a> { |
| 60 | + inner: PartInner<'a>, |
| 61 | + meta: PartMeta, |
| 62 | +} |
| 63 | + |
| 64 | +enum PartInner<'a> { |
| 65 | + Borrowed(SendBody<'a>), |
| 66 | + Owned(SendBody<'static>), |
| 67 | +} |
| 68 | + |
| 69 | +struct PartMeta { |
| 70 | + mime: Option<Mime>, |
| 71 | + file_name: Option<String>, |
| 72 | + headers: http::HeaderMap, |
| 73 | +} |
| 74 | + |
| 75 | +impl<'a> Form<'a> { |
| 76 | + /// Creates a new async Form without any content. |
| 77 | + pub fn new() -> Self { |
| 78 | + // Generate a random boundary using fastrand |
| 79 | + use std::iter::repeat_with; |
| 80 | + let mut boundary = String::with_capacity(BOUNDARY_PREFIX.len() + BOUNDARY_SUFFIX_LEN); |
| 81 | + boundary.push_str(BOUNDARY_PREFIX); |
| 82 | + boundary.extend(repeat_with(fastrand::alphanumeric).take(BOUNDARY_SUFFIX_LEN)); |
| 83 | + |
| 84 | + Form { |
| 85 | + parts: Vec::new(), |
| 86 | + boundary, |
| 87 | + state: ReadState::default(), |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + /// Get the boundary that this form will use. |
| 92 | + pub fn boundary(&self) -> &str { |
| 93 | + &self.boundary |
| 94 | + } |
| 95 | + |
| 96 | + /// Add a data field with supplied name and value. |
| 97 | + pub fn text(mut self, name: &'a str, value: &'a str) -> Self { |
| 98 | + let part = Part::text(value); |
| 99 | + self.parts.push((name, part)); |
| 100 | + self |
| 101 | + } |
| 102 | + |
| 103 | + /// Adds a file field. |
| 104 | + pub async fn file<P: AsRef<Path>>(mut self, name: &'a str, path: P) -> std::io::Result<Self> { |
| 105 | + let part = Part::file(path).await?; |
| 106 | + self.parts.push((name, part)); |
| 107 | + Ok(self) |
| 108 | + } |
| 109 | + |
| 110 | + /// Adds a customized Part. |
| 111 | + pub fn part(mut self, name: &'a str, part: Part<'a>) -> Self { |
| 112 | + self.parts.push((name, part)); |
| 113 | + self |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +impl<'a> Part<'a> { |
| 118 | + /// Create a text part. |
| 119 | + pub fn text(text: &'a str) -> Self { |
| 120 | + Part { |
| 121 | + inner: PartInner::Borrowed(SendBody::from_bytes(text.as_bytes())), |
| 122 | + meta: PartMeta { |
| 123 | + mime: None, |
| 124 | + file_name: None, |
| 125 | + headers: http::HeaderMap::new(), |
| 126 | + }, |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + /// Create a part from bytes. |
| 131 | + pub fn bytes(bytes: &'a [u8]) -> Self { |
| 132 | + Part { |
| 133 | + inner: PartInner::Borrowed(SendBody::from_bytes(bytes)), |
| 134 | + meta: PartMeta { |
| 135 | + mime: None, |
| 136 | + file_name: None, |
| 137 | + headers: http::HeaderMap::new(), |
| 138 | + }, |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + /// Create a part from a reader. |
| 143 | + pub fn reader(reader: &'a mut dyn Read) -> Self { |
| 144 | + Part { |
| 145 | + inner: PartInner::Borrowed(SendBody::from_reader(reader)), |
| 146 | + meta: PartMeta { |
| 147 | + mime: None, |
| 148 | + file_name: None, |
| 149 | + headers: http::HeaderMap::new(), |
| 150 | + }, |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + /// Create a part from an owned reader. |
| 155 | + pub fn owned_reader(reader: impl Read + 'static) -> Part<'a> { |
| 156 | + Part { |
| 157 | + inner: PartInner::Owned(SendBody::from_owned_reader(reader)), |
| 158 | + meta: PartMeta { |
| 159 | + mime: None, |
| 160 | + file_name: None, |
| 161 | + headers: http::HeaderMap::new(), |
| 162 | + }, |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + /// Create a part from a file. |
| 167 | + pub async fn file<P: AsRef<Path>>(path: P) -> std::io::Result<Part<'a>> { |
| 168 | + let mime = mime_guess::from_path(&path).first(); |
| 169 | + let file_name = path |
| 170 | + .as_ref() |
| 171 | + .file_name() |
| 172 | + .map(|filename| filename.to_string_lossy().into_owned()); |
| 173 | + let file = std::fs::File::open(path)?; |
| 174 | + Ok(Part { |
| 175 | + inner: PartInner::Owned(SendBody::from_file(file)), |
| 176 | + meta: PartMeta { |
| 177 | + mime, |
| 178 | + file_name, |
| 179 | + headers: http::HeaderMap::new(), |
| 180 | + }, |
| 181 | + }) |
| 182 | + } |
| 183 | + |
| 184 | + /// Set the file name for this part. |
| 185 | + pub fn file_name(mut self, name: &str) -> Self { |
| 186 | + self.meta.file_name = Some(name.to_string()); |
| 187 | + self |
| 188 | + } |
| 189 | + |
| 190 | + /// Set the MIME type for this part. |
| 191 | + pub fn mime_str(mut self, mime: &str) -> Self { |
| 192 | + if let Ok(mime_type) = mime.parse() { |
| 193 | + self.meta.mime = Some(mime_type); |
| 194 | + } |
| 195 | + self |
| 196 | + } |
| 197 | + |
| 198 | + /// Get the headers for this part. |
| 199 | + pub fn headers(&self) -> &http::HeaderMap { |
| 200 | + &self.meta.headers |
| 201 | + } |
| 202 | +} |
| 203 | + |
| 204 | +impl<'a> Private for Form<'a> {} |
| 205 | +impl<'a> AsSendBody for Form<'a> { |
| 206 | + fn as_body(&mut self) -> SendBody { |
| 207 | + // TODO(martin): here we should be able to know the size of the body |
| 208 | + // and therefore use (some new) constructor in SendBody that sets the size. |
| 209 | + SendBody::from_reader(self) |
| 210 | + } |
| 211 | +} |
| 212 | + |
| 213 | +#[derive(Default)] |
| 214 | +struct ReadState { |
| 215 | + // TODO(martin) |
| 216 | +} |
| 217 | + |
| 218 | +impl io::Read for Form<'_> { |
| 219 | + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 220 | + // TODO(martin): implement a streaming reader of the multipart body. |
| 221 | + todo!() |
| 222 | + } |
| 223 | +} |
0 commit comments