![CI-badge] ![Latest Version] ![Docs Badge]
Provides a FromMultipart
derive for construct types from multer::Multipart.
```rs use multer_derive::{FormFile, FromMultipart, Multipart, MultipartForm};
struct Person { name: String, email: String, age: u8, married: bool, photo: FormFile }
const FORMDATA : &str = "--boundarystring\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nJohn Smith\r\n--boundarystring\r\nContent-Disposition: form-data; name=\"email\"\r\n\r\njohn@example.com\r\n--boundarystring\r\nContent-Disposition: form-data; name=\"age\"\r\n\r\n25\r\n--boundarystring\r\nContent-Disposition: form-data; name=\"married\"\r\n\r\ntrue\r\n--boundarystring\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"example.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n[Binary data]\r\n--boundary_string--\r\n";
let reader = FORMDATA.asbytes(); let multipart = Multipart::withreader(reader, "boundarystring");
let form = MultipartForm::withmultipart(multipart).await.unwrap(); let person = Person::frommultipart(form).unwrap();
asserteq!(person.name, "John Smith"); asserteq!(person.email, "john@example.com"); asserteq!(person.age, 25); asserteq!(person.married, true);
let str = String::fromutf8(person.photo.bytes().tovec()).unwrap(); assert_eq!(str, "[Binary data]"); ```
multer-derive
also support the next attributes to decorate your fields:
#[multer(rename = "new_field_name")]
Example:
```rs use multer_derive::FromMultipart;
struct MyStruct { #[multer(rename = "active")] is_active: bool } ```
To parse using a function you can use #[multer(with = "path::to::function")]
rs
fn from_multipart(multipart: &MultipartForm, ctx: FormContext<'_>) -> Result<YourType, Error> {
todo!()
}
Example:
```rs use multer_derive::{FromMultipart, MultipartForm, FormContext, Error};
struct MyStruct { #[multer(with = "textfrommultipart")] name: Text }
struct Text(String);
fn textfrommultipart(
multipart: &MultipartForm,
ctx: FormContext<'>,
) -> Resultfield_name
is always passed
let field
// We search the field in the source multipart
let field = multipart
.get_by_name(field_name)
.ok_or(Error::new(format!(
"`{field_name}` form field was not found"
)))?;
// Parse the value using `String`
let s = String::from_field(field)?;
Ok(Text(s))
} ```