Expand description
Type-safe multipart/form-data handling for Axum.
§Installation
cargo add axum_typed_multipart§Features
All features are enabled by default.
chrono_0_4: Enables support for chrono::DateTime (v0.4)tempfile_3: Enables support for tempfile::NamedTempFile (v3)uuid_1: Enables support for uuid::Uuid (v1)rust_decimal_1: Enables support for rust_decimal::Decimal (v1)
§Usage
§Getting started
To get started you will need to define a struct with the desired fields and implement the TryFromMultipart trait. In the vast majority of cases you will want to use the derive macro to generate the implementation automatically.
To be able to derive the TryFromMultipart trait every field in the struct must implement the TryFromField trait.
The TryFromField trait is implemented by default for the following types:
- i8, i16, i32, i64, i128, isize
- u8, u16, u32, u64, u128, usize
- f32, f64
- bool
- char
- String
- axum::body::Bytes
- chrono::DateTime (feature:
chrono_0_4) - chrono::NaiveDate (feature:
chrono_0_4) - tempfile::NamedTempFile (feature:
tempfile_3) - uuid::Uuid (feature:
uuid_1) - rust_decimal::Decimal (feature:
rust_decimal_1)
If the request body is malformed the request will be aborted with an error.
An error will be returned if at least one field is missing, except for Option and
Vec types, which will be set respectively as None and [].
use axum::http::StatusCode;
use axum::routing::post;
use axum::Router;
use axum_typed_multipart::{TryFromMultipart, TypedMultipart};
#[derive(TryFromMultipart)]
struct CreateUserRequest {
first_name: String,
last_name: String,
}
async fn create_user(data: TypedMultipart<CreateUserRequest>) -> StatusCode {
println!("name: '{} {}'", data.first_name, data.last_name); // Your logic here.
StatusCode::CREATED
}
pub fn app() -> Router {
Router::new().route("/users/create", post(create_user))
}
#[tokio::main]
async fn main() {
let port = std::env::var("PORT").unwrap_or("0".into());
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}")).await.unwrap();
println!("Listening on http://{}", listener.local_addr().unwrap());
axum::serve(listener, app()).await.unwrap();
}§Optional fields
If a field is declared as an Option the value will default to None when the field is missing from the request body.
use axum_typed_multipart::TryFromMultipart;
#[derive(TryFromMultipart)]
struct RequestData {
first_name: Option<String>,
}§Renaming fields
If you would like to assign a custom name for the source field you can use the field_name
parameter of the form_data attribute.
use axum_typed_multipart::TryFromMultipart;
#[derive(TryFromMultipart)]
struct RequestData {
#[form_data(field_name = "first_name")]
name: Option<String>,
}The rename_all parameter from the try_from_multipart attribute can be used to automatically
rename each field of your struct to a specific case. It works the same way as
#[serde(rename_all = "...")].
Supported cases:
snake_casecamelCasePascalCasekebab-caseUPPERCASElowercase
use axum_typed_multipart::TryFromMultipart;
#[derive(TryFromMultipart)]
#[try_from_multipart(rename_all = "UPPERCASE")]
struct RequestData {
name: Option<String>, // Will be renamed to `NAME` in the request.
}NOTE: If the #[form_data(field_name = "...")] attribute is specified, the rename_all rule
will not be applied.
§Default values
If the default parameter in the form_data attribute is present the value will be populated
using the type’s Default implementation when the field is not supplied in the request.
use axum_typed_multipart::TryFromMultipart;
#[derive(TryFromMultipart)]
struct RequestData {
#[form_data(default)]
name: String, // defaults to ""
}§Field metadata
If you need access to the field metadata (e.g. the field headers like file name or content type) you can use the FieldData struct to wrap your field.
use axum::body::Bytes;
use axum_typed_multipart::{FieldData, TryFromMultipart};
#[derive(TryFromMultipart)]
struct RequestData {
image: FieldData<Bytes>,
}§Field size limits
By default, there are no size limits on individual fields. You can set a limit using the
limit parameter of the form_data attribute. The limit accepts human-readable byte units
(e.g., "1MB", "512KB", "1GiB") or "unlimited" to explicitly disable limits.
use axum_typed_multipart::TryFromMultipart;
#[derive(TryFromMultipart)]
struct RequestData {
#[form_data(limit = "1MB")]
small_file: Vec<u8>,
#[form_data(limit = "unlimited")]
large_file: Vec<u8>,
}§Large uploads
For large uploads you can save the contents of the field to the file system using tempfile::NamedTempFile. This will efficiently stream the field data directly to the file system, without needing to fit all the data in memory. Once the upload is complete, you can then save the contents to a location of your choice. For more information check out the NamedTempFile documentation.
§Note
When handling large uploads you will need to increase the request body size limit using the DefaultBodyLimit middleware.
use axum::extract::DefaultBodyLimit;
use axum::http::StatusCode;
use axum::routing::post;
use axum::Router;
use axum_typed_multipart::{FieldData, TryFromMultipart, TypedMultipart};
use tempfile_3::NamedTempFile;
#[derive(TryFromMultipart)]
struct UploadAssetRequest {
// Field size limits are disabled by default. The `limit` parameter can be used
// to set a specific size limit in bytes, like '5MiB' or '1GiB'. The value
// "unlimited" explicitly disables the limit (same as the default behavior).
#[form_data(limit = "unlimited")]
image: FieldData<NamedTempFile>,
// This field has no size limit since limits are disabled by default.
author: String,
}
async fn upload_asset(
TypedMultipart(UploadAssetRequest { image, author }): TypedMultipart<UploadAssetRequest>,
) -> StatusCode {
let dir = tempfile_3::tempdir().unwrap();
let file_name = image.metadata.file_name.unwrap_or(String::from("data.bin"));
let path = dir.path().join(format!("{author}_{file_name}"));
match image.contents.persist(path) {
Ok(_) => StatusCode::CREATED,
Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
pub fn app() -> Router {
Router::new()
.route("/", post(upload_asset))
// The default axum body size limit is 2MiB, so we increase it to 1GiB.
.layer(DefaultBodyLimit::max(1024 * 1024 * 1024))
}
#[tokio::main]
async fn main() {
let port = std::env::var("PORT").unwrap_or("0".into());
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}")).await.unwrap();
println!("Listening on http://{}", listener.local_addr().unwrap());
axum::serve(listener, app()).await.unwrap();
}§Lists
If the incoming request will include multiple fields that share the same name (AKA lists) the field can be declared as a Vec, allowing for all occurrences of the field to be stored.
§Warning
Field size limits for Vec fields are applied to each occurrence of the field. This means that if you have a 1GiB field limit and the field contains 5 entries, the total size of the request body will be 5GiB.
use axum::http::StatusCode;
use axum_typed_multipart::{TryFromMultipart, TypedMultipart};
#[derive(TryFromMultipart)]
struct RequestData {
names: Vec<String>,
}§Strict mode
By default, the derive macro will store the last occurrence of a field, and it will ignore
unknown fields. This behavior can be changed by using the strict parameter in the derive
macro. This will make the macro throw an error if the request contains multiple fields with the
same name or if it contains unknown fields. In addition, when using strict mode sending fields
with a missing or empty name will result in an error.
use axum_typed_multipart::TryFromMultipart;
#[derive(TryFromMultipart)]
#[try_from_multipart(strict)]
struct RequestData {
name: String,
}§Enums
axum_typed_multipart also supports custom enum parsing by deriving the
TryFromField trait:
use axum_typed_multipart::{TryFromField, TryFromMultipart};
#[derive(TryFromField)]
enum Sex {
Male,
Female,
}
#[derive(TryFromMultipart)]
struct Person {
name: String,
sex: Sex,
}Enum fields can be renamed in two ways:
use axum_typed_multipart::TryFromField;
#[derive(TryFromField)]
// Using the `#[try_from_field(rename_all = "...")]` renaming attribute.
// Works the same way as the `TryFromMultipart` implementation.
#[try_from_field(rename_all = "snake_case")]
enum AccountType {
// Or using the `#[field(rename = "...")]` attribute.
#[field(rename = "administrator")]
Admin,
Moderator,
Plain
}§Custom types
If you would like to use a custom type for a field you need to implement the TryFromField trait for your type. This will allow the derive macro to generate the TryFromMultipart implementation automatically. Instead of implementing the trait directly, it is recommended to implement the TryFromChunks trait, which will automatically provide a TryFromField implementation with proper size limit handling.
To implement the TryFromChunks trait for external types you will need to create a newtype wrapper and implement the trait for the wrapper.
§Custom error format
When using TypedMultipart as an argument for your handlers, errors are serialized as strings. To customize the error format, use BaseMultipart instead.
To customize the error you will need to define a custom error type and implement
IntoResponse and From<TypedMultipartError>.
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::{Json, Router};
use axum_typed_multipart::{BaseMultipart, TryFromMultipart, TypedMultipartError};
use serde::Serialize;
// Step 1: Define a custom error type.
#[derive(Serialize)]
struct CustomError {
message: String,
status: u16,
}
// Step 2: Implement `IntoResponse` for the custom error type.
impl IntoResponse for CustomError {
fn into_response(self) -> Response {
let status = StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
(status, Json(self)).into_response()
}
}
// Step 3: Implement `From<TypedMultipartError>` for the custom error type.
impl From<TypedMultipartError> for CustomError {
fn from(error: TypedMultipartError) -> Self {
Self { message: error.to_string(), status: error.get_status().into() }
}
}
// Step 4: Define a type alias for the multipart request (Optional).
type CustomMultipart<T> = BaseMultipart<T, CustomError>;
#[derive(TryFromMultipart)]
struct UpdatePositionRequest {
name: String,
position: u32,
}
// Step 5: Define a handler that takes the custom multipart as argument.
// If the request is malformed, a `CustomError` will be returned.
async fn update_position(data: CustomMultipart<UpdatePositionRequest>) -> StatusCode {
println!("name = '{}'", data.name);
println!("position = '{}'", data.position);
StatusCode::OK
}
pub fn app() -> Router {
Router::new().route("/position/update", post(update_position))
}
#[tokio::main]
async fn main() {
let port = std::env::var("PORT").unwrap_or("0".into());
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}")).await.unwrap();
println!("Listening on http://{}", listener.local_addr().unwrap());
axum::serve(listener, app()).await.unwrap();
}§Injecting state into the parser
Sometimes you may need to access application state during field parsing. This is supported through the TryFromFieldWithState trait.
use axum::http::StatusCode;
use axum::routing::post;
use axum::Router;
use axum_typed_multipart::{TypedMultipart, TypedMultipartError};
use axum_typed_multipart_macros::TryFromMultipart;
/// A field that validates its value against application state.
#[derive(Debug)]
struct ValidatedField(String);
/// Application state containing validation rules.
#[derive(Clone)]
struct State {
allowed_values: Vec<String>,
}
#[async_trait::async_trait]
impl axum_typed_multipart::TryFromFieldWithState<State> for ValidatedField {
async fn try_from_field_with_state(
mut field: axum::extract::multipart::Field<'_>,
limit_bytes: Option<usize>,
state: &State,
) -> Result<Self, TypedMultipartError> {
let mut value = String::new();
while let Some(chunk) = field.chunk().await.map_err(anyhow::Error::from)? {
// SECURITY: Manual size limit handling is required for TryFromFieldWithState.
// Unlike TryFromField which can leverage TryFromChunks for automatic size checking,
// the stateful variant requires explicit implementation.
//
// When limit_bytes will be None:
// - Your type is private (not exposed in public API) AND
// - You don't use #[form_data(limit = "...")] on fields of this type
// In this case, you control all usage and can skip size checking if appropriate.
//
// When limit_bytes may have a value:
// - Your type is public (part of your API), OR
// - You use #[form_data(limit = "...")] on any field of this type
// You MUST enforce the limit to prevent denial-of-service attacks from unbounded uploads.
if let Some(limit) = limit_bytes {
if value.len() + chunk.len() > limit {
return Err(TypedMultipartError::FieldTooLarge {
field_name: field.name().unwrap_or("unknown").to_string(),
limit_bytes: limit,
});
}
}
value.push_str(std::str::from_utf8(&chunk).map_err(anyhow::Error::from)?);
}
if state.allowed_values.contains(&value) {
Ok(ValidatedField(value))
} else {
Err(TypedMultipartError::Other {
source: anyhow::anyhow!("Value '{}' is not allowed", value),
})
}
}
}
#[derive(TryFromMultipart)]
#[try_from_multipart(state = State)]
struct UpdateUserRequest {
#[form_data(limit = "100B")]
role: ValidatedField,
}
async fn update_user(TypedMultipart(data): TypedMultipart<UpdateUserRequest>) -> StatusCode {
println!("User role updated to: '{}'", data.role.0);
StatusCode::OK
}
pub fn app() -> Router {
let allowed_roles = ["admin", "editor", "viewer", "guest"];
let state =
State { allowed_values: allowed_roles.into_iter().map(ToString::to_string).collect() };
Router::new().route("/user/update", post(update_user)).with_state(state)
}
#[tokio::main]
async fn main() {
let port = std::env::var("PORT").unwrap_or("0".into());
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}")).await.unwrap();
println!("Listening on http://{}", listener.local_addr().unwrap());
axum::serve(listener, app()).await.unwrap();
}§Usage with utoipa
utoipa can be used to add documentation and automatically
generate openapi.json specifications. See the utoipa example
for integration details.
Note: File uploads in utoipa require Vec<u8> which differs from this crate’s Bytes or
tempfile::NamedTempFile. The example shows how to handle this.
§Validation
For field validation, consider using the validator crate with axum-valid. See the axum-valid docs for examples.
Re-exports§
pub use anyhow;
Structs§
- Base
Multipart - Base extractor for multipart form data with custom error handling.
- Field
Data - Wrapper that provides access to both field contents and metadata.
- Field
Metadata - Additional information about the file supplied by the client in the request.
- Typed
Multipart - Extractor for type-safe multipart form data in Axum Handlers.
Enums§
- Typed
Multipart Error - Error type for multipart parsing operations.
Traits§
- TryFrom
Chunks - Types that can be created from a Stream of Bytes.
- TryFrom
Field - Types that can be created from a multipart field.
- TryFrom
Field With State - Stateful variant of TryFromField that provides access to application state during parsing.
- TryFrom
Multipart - Types that can be created from multipart form data.
- TryFrom
Multipart With State - Stateful variant of TryFromMultipart that provides access to application state during parsing.