1mod error;
2mod field;
3mod reader;
4mod file_form;
5
6use crate::error::HlsResult;
7use crate::form_data::field::FormField;
8use crate::reader::RefReader;
9pub use error::FormError;
10pub use reader::HttpFileReader;
11use reqrio_json::JsonValue;
12use std::path::Path;
13use std::sync::Arc;
14pub use file_form::FileForm;
15
16
17pub struct HttpFile {
18 data: Vec<FormField>,
19 forms: Vec<FileForm>,
20 boundary: Arc<String>,
21}
22
23impl Default for HttpFile {
24 fn default() -> Self {
25 HttpFile {
26 data: vec![],
27 forms: vec![],
28 boundary: Arc::new(String::new()),
29 }
30 }
31}
32
33impl HttpFile {
34 #[inline]
35 pub fn new_bytes(bytes: impl Into<Vec<u8>>) -> HttpFile {
36 HttpFile::new_bytes_data(JsonValue::Null, bytes)
37 }
38
39 pub fn new_bytes_data(data: JsonValue, bytes: impl Into<Vec<u8>>) -> HttpFile {
40 HttpFile {
41 data: data.into_entries().map(|(k, v)| FormField::new(k, v.dump())).collect(),
42 forms: vec![FileForm::new_bytes(bytes)],
43 boundary: Arc::new("".to_string()),
44 }
45 }
46
47 #[inline]
48 pub fn new_path(path: impl AsRef<Path>) -> HlsResult<HttpFile> {
49 HttpFile::new_path_data(JsonValue::Null, path)
50 }
51
52 pub fn new_path_data(data: JsonValue, path: impl AsRef<Path>) -> HlsResult<HttpFile> {
53 Ok(HttpFile {
54 data: data.into_entries().map(|(k, v)| FormField::new(k, v.dump())).collect(),
55 forms: vec![FileForm::new_path(path)?],
56 boundary: Arc::new("".to_string()),
57 })
58 }
59
60 #[inline]
61 pub fn new_form(form: FileForm) -> HttpFile {
62 HttpFile::new_form_data(JsonValue::Null, form)
63 }
64
65 pub fn new_form_data(data: JsonValue, form: FileForm) -> HttpFile {
66 HttpFile {
67 data: data.into_entries().map(|(k, v)| FormField::new(k, v.dump())).collect(),
68 forms: vec![form],
69 boundary: Arc::new("".to_string()),
70 }
71 }
72
73 #[inline]
74 pub fn with_boundary(mut self, boundary: Arc<String>) -> HttpFile {
75 self.set_boundary(boundary);
76 self
77 }
78
79 #[inline]
80 pub fn set_boundary(&mut self, boundary: Arc<String>) {
81 self.boundary = boundary;
82 }
83
84 #[inline]
85 pub fn add_form(&mut self, form: FileForm) {
86 self.forms.push(form);
87 }
88
89 #[inline]
90 pub fn remove_form(&mut self, index: usize) -> FileForm {
91 self.forms.remove(index)
92 }
93
94 #[inline]
95 pub fn forms(&self) -> &[FileForm] {
96 &self.forms
97 }
98
99 pub(crate) fn as_reader(&self) -> HlsResult<HttpFileReader<'_>> {
100 let mut suffix_reader: RefReader<&[u8]> = RefReader::default();
101 suffix_reader.add_buf(b"--");
102 suffix_reader.add_buf(self.boundary.as_bytes());
103 suffix_reader.add_buf(b"--");
105 let mut files = vec![];
106 for form in &self.forms {
107 files.push(form.as_form_render(&self.boundary)?);
108 }
109 Ok(HttpFileReader {
110 data_readers: self.data.iter().map(|x| x.as_render(&self.boundary)).collect(),
111 files,
112 suffix_reader,
113 row: 0,
114 pos: 0,
115 wrote: false,
116 })
117 }
118}
119