Skip to content

Uploads ​

With the multipart feature, Upload<T> reads a multipart/form-data body into one struct, validates it and documents it. It turns on garde.

toml
axum-autodoc = { version = "0.2", features = ["multipart"] }

One struct for the form ​

Text fields, numbers, booleans and lists are plain fields. A file is a File, which keeps the file name, the content type and the bytes:

rust
#[derive(Debug, Deserialize, Validate, JsonSchema)]
pub struct NewAvatar {
    #[garde(skip)]
    pub image: File,
    #[garde(length(max = 100))]
    pub caption: Option<String>,
}
rust
#[api(
    summary = "Upload an avatar",
    description = "A multipart form with the image and an optional caption."
)]
pub async fn upload_avatar(
    State(state): State<AppState>,
    Params(path): Params<UserPath>,
    Upload(form): Upload<NewAvatar>,
) -> Result<Status<201, Json<AvatarResponse>>, FindUserError> {
    state.users.find_user(UserId(path.id)).await?;
    Ok(Status(Json(AvatarResponse {
        bytes: form.image.bytes.len(),
        content_type: form.image.content_type,
        caption: form.caption,
    })))
}

A Vec<File> takes several files under one name, and an Option<File> makes the file optional. Fields are coerced the same way a query string is, so age=3 fills a u8. A repeated name fills a Vec.

What gets documented ​

  • the request body as multipart/form-data, with a File field as { "type": "string", "format": "binary" } and a Vec<File> as an array of those,
  • 400, 413 and 415 with RequestRejection, as for Body<T>.

A body that is not multipart/form-data answers 415. A failed validation, a missing field, a file where text was expected and an unreadable form all answer 400 with the same body as the other validated extractors. A form over axum's body limit answers 413, so raise DefaultBodyLimit for large files.

Plain Multipart

axum's own Multipart still works. It is documented as multipart/form-data with an object schema and no fields, since nothing says what the handler reads.

The TypeScript client takes the same struct as a FormData body.

Released under the MIT or Apache-2.0 license.