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
use std::path::Path;

use uuid::Uuid;

/// Simple builder for multipart/form-data test
///
/// # Examples
///
/// ```
/// #[cfg(test)]
/// mod tests {
///     use actix_multipart_test::MultiPartFormDataBuilder;
///     use actix_web::{test, App};
///     use super::*;
///
///     #[actix_web::test]
///     async fn test_should_upload_file() {
///
///         let mut app =
///             test::init_service(
///                     App::new()
///                     .service(yourmultipartformhandler)
///                 )
///                 .await;
///
///         let mut multipart_form_data_builder = MultiPartFormDataBuilder::new();
///         multipart_form_data_builder.with_file("tests/sample.png", "sample", "image/png", "sample.png");
///         multipart_form_data_builder.with_text("name", "some_name");
///         let (header, body) = multipart_form_data_builder.build();
///
///
///         let req = test::TestRequest::post()
///             .uri("/someurl")
///             .insert_header(header)
///             .set_payload(body)
///             .to_request();
///         let resp = test::call_service(&mut app, req).await;
///
///         assert!(resp.status().is_success());
///
///     }
/// }
/// ```
pub struct MultiPartFormDataBuilder {
    files: Vec<(String, String, String, Box<dyn AsRef<Path>>)>,
    texts: Vec<(String, String, String)>,
}

impl MultiPartFormDataBuilder {
    /// Create new MultiPartFormDataBuilder
    pub fn new() -> MultiPartFormDataBuilder {
        MultiPartFormDataBuilder {
            files: vec![],
            texts: vec![],
        }
    }

    /// Add text to multipart/form-data
    ///
    /// name is form name
    ///
    /// value is form value
    ///
    /// Returns &mut MultiPartFormDataBuilder
    pub fn with_text(
        &mut self,
        name: impl Into<String>,
        value: impl Into<String>,
    ) -> &mut MultiPartFormDataBuilder {
        self.texts
            .push((name.into(), value.into(), "text/plain".to_string()));
        self
    }

    /// Add file to multipart/form-data
    ///
    /// path is file path
    ///
    /// name is form name
    ///
    /// content_type is file content type
    ///
    /// file_name is file name
    pub fn with_file(
        &mut self,
        path: impl AsRef<Path> + 'static,
        name: impl Into<String>,
        content_type: impl Into<String>,
        file_name: impl Into<String>,
    ) -> &mut MultiPartFormDataBuilder {
        self.files.push((
            name.into(),
            file_name.into(),
            content_type.into(),
            Box::new(path),
        ));
        self
    }

    /// Build multipart/form-data
    ///
    /// Returns ((header_name, header_value), body)
    ///
    /// header_name is "Content-Type"
    ///
    /// header_value is "multipart/form-data; boundary=..."
    ///
    /// body is binary data
    pub fn build(&self) -> ((String, String), Vec<u8>) {
        let boundary = Uuid::new_v4().to_string();

        let mut body = vec![];

        for file in self.files.iter() {
            body.extend(format!("--{}\r\n", boundary).as_bytes());
            body.extend(
                format!(
                    "Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"\r\n",
                    file.0, file.1
                )
                .as_bytes(),
            );
            body.extend(format!("Content-Type: {}\r\n", file.2).as_bytes());
            let data = std::fs::read(file.3.as_ref()).unwrap();
            body.extend(format!("Content-Length: {}\r\n\r\n", data.len()).as_bytes());
            body.extend(data);
            body.extend("\r\n".as_bytes());
        }

        for text in self.texts.iter() {
            body.extend(format!("--{}\r\n", boundary).as_bytes());
            body.extend(
                format!("Content-Disposition: form-data; name=\"{}\"\r\n", text.0).as_bytes(),
            );
            body.extend(format!("Content-Type: {}\r\n", text.2).as_bytes());
            let data = text.1.as_bytes();
            body.extend(format!("Content-Length: {}\r\n\r\n", data.len()).as_bytes());
            body.extend(data);
            body.extend("\r\n".as_bytes());
        }

        body.extend(format!("--{}\r\n", boundary).as_bytes());

        let header_value = format!("multipart/form-data; boundary={}", boundary);
        let header = ("Content-Type".to_string(), header_value);

        (header, body)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_should_build_multipart_form_with_text() {
        let mut multipart_form_data_builder = MultiPartFormDataBuilder::new();
        multipart_form_data_builder.with_file(
            "tests/sample.png",
            "sample",
            "image/png",
            "sample.png",
        );
        multipart_form_data_builder.with_text("name", "some_name");
        let (header, body) = multipart_form_data_builder.build();

        assert_eq!(header.0, "Content-Type");
        assert!(header.1.starts_with("multipart/form-data; boundary="));
        assert!(body.len() > 0);
    }
}