Functions and structures to handle actix multipart more easily. You can convert the multipart into a struct.
To use this function, you need to create a structure with "Deserialize" trait, like this: ```rust
struct example {
stringparam: String,
optionaluparam: Option
File is a structure for any files:
rust
pub struct File {
filetype: FileType,
name: String,
size: u64,
data: FileData,
}
impl File {
pub fn filetype(&self) -> &FileType {
&self.filetype
}
pub fn name(&self) -> &String {
&self.name
}
pub fn len(&self) -> u64 {
self.size
}
pub fn data(&self) -> &FileData {
&self.data
}
}
FileData is an alias to Vec<u8> bytes: (Defined in multipart.rs file)
rust
pub type FileData = Vec
rust
async fn extract_multipart::<StructureType: T>(actix_mutlipart::Multipart) -> Result<T, _>
```rust use actixweb::{post, App, HttpResponse, HttpServer}; use serde::{Deserialize}; use actixmultipart::Multipart;
use actixextractmultipart::*;
struct example {
stringparam: String,
optionaluparam: Option
fn savingfilefunction(file: File) -> Result<(), ()> { // Do some stuff here println!("Saving file \"{}\" successfully", file.name());
Ok(())
}
async fn index(payload: Multipart) -> HttpResponse {
let examplestructure = match extractmultipart::
println!("Value of string_param: {}", example_structure.string_param);
println!("Value of optional_u_param: {:?}", example_structure.optional_u_param);
println!("Having file? {}", match example_structure.file_param {
Some(_) => "Yes",
None => "No"
});
if let Some(file) = example_structure.file_param {
match saving_file_function(file) {
Ok(_) => println!("File saved!"),
Err(_) => println!("An error occured while file saving")
}
}
HttpResponse::Ok().json("Done")
}
async fn main() -> std::io::Result<()> { println!("Server run at http://127.0.0.1:8080");
HttpServer::new(move || {
App::new()
.service(index)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
In this example, if you dont have received a file, extract_multipart will return an Err(_), because data don't correspond to the data struct "example".
If the File is optional, you can simply set the type as Option<File>, like this:
rust
struct example {
stringparam: String,
optionaluparam: Option
The function extract_multipart will return Err(_) value also if the file type was not in FileType enumeration.
pub enum FileType { ImagePNG, ImageJPEG, ImageGIF, ImageWEBP, ApplicationPDF, ApplicationJSON, ApplicationXML, TextCSV, TextPlain, #[serde(alias = "applicationvndoasisopendocumenttext")] ODT, #[serde(alias = "applicationvndoasisopendocumentspreadsheet")] ODS, #[serde(alias = "applicationvndmsexcel")] XLS, #[serde(alias = "applicationvndopenxmlformatsofficedocumentspreadsheetmlsheet")] XLSX, } ```