Axum Multipart Feature

Learn how to enable and use the axum multipart feature to handle multipart-form-data requests such as file uploads and mixed data forms

When you build an HTTP server, most of the requests you receive will be simple: a JSON body, a form, or just a URL with some query parameters. But there is a whole category of requests that need to carry binary data or multiple pieces of very different data at once - the most common example is a file upload. A user picks a file on their computer, a browser sends that file to your server, and maybe it also sends a text description, a checkbox value, and a username all in the same request. That kind of request uses a format called multipart/form-data. Axum does not include support for parsing this format by default. You must opt in by enabling the multipart feature flag when you declare the axum dependency. This page explains exactly what that feature flag does, why it exists, how to turn it on, and how to use the result in a small but complete example.

What the multipart Feature Enables

Axum is built around the idea of being modular. The core crate handles routing, handlers, and basic request parsing, but many capabilities are optional and must be turned on through Cargo features. The multipart feature is one of those optional capabilities. When you enable it, Axum pulls in a separate crate called multer, which is a streaming parser for multipart/form-data bodies. Axum then exposes a new extractor type named Multipart that you can use as a parameter in your handler functions. That extractor gives you access to the individual parts - called fields - of the incoming request, including both text fields and uploaded files.

Without this feature, the axum::extract::Multipart type does not exist. If you try to write a handler that takes Multipart as an argument, the Rust compiler will stop with an error telling you the type cannot be found. That is not because you wrote the code incorrectly; it is because the necessary code was never compiled into your project. Enabling the feature tells Cargo to include the multer dependency and all the glue code that connects it to Axum's extractor system.

Extractors in Axum:

In Axum, an extractor is a special type that knows how to pull information out of an incoming request. Json, Query, Path, and State are all extractors. They appear as arguments to your handler function, and Axum calls the right logic automatically to build them from the raw HTTP request.

The multipart feature does not add any new routing methods or middleware. It only adds the Multipart extractor and its supporting types, like Field. Everything else about your Axum application stays the same.

Why Multipart Requests Need Special Handling

To understand why this feature exists as a separate flag, it helps to look at the format itself. A normal application/x-www-form-urlencoded form sends key-value pairs as a single string like name=Alice&age=30. Parsing that is easy - split on &, then split on =. JSON is also just a string with a defined structure. But multipart/form-data is different. Each field is separated by a special boundary string, and each part has its own headers. For example, a request might look like this at the raw byte level:

--boundary123
Content-Disposition: form-data; name="username"
alice
--boundary123
Content-Disposition: form-data; name="avatar"; filename="cat.jpg"
Content-Type: image/jpeg
(binary image bytes)
--boundary123--

The boundary string is chosen by the client and included in the Content-Type header of the request. The server must find that boundary, split the body at each occurrence, parse the headers inside each part, and then expose the data. This is a non-trivial parsing task, and it also has to deal with large files that might be hundreds of megabytes. A naive parser that loads the entire body into memory before splitting could crash your server when a user uploads a large video. The multer crate solves this by parsing the stream incrementally, allowing you to process each field as it arrives.

Because this parsing logic is complex and not needed by every Axum application, the Axum maintainers decided to keep it behind a feature flag. If your application only serves JSON APIs, you never pay the compilation cost or binary size cost of including the multipart parser.

How to Enable the multipart Feature

Enabling the feature is a simple change to your Cargo.toml file. Your project already has an axum dependency. The exact line depends on how you originally added Axum. The most common form is:

Cargo.toml
[dependencies]
axum = { version = "0.8", features = ["multipart"] }

If you already have other features enabled, you add "multipart" to the existing list inside the square brackets. For example, if you already enabled the macros feature, your line might now look like this:

Cargo.toml
[dependencies]
axum = { version = "0.8", features = ["macros", "multipart"] }

You can also use Cargo's command line to add the feature without manually editing the file. If you want to keep your existing features and add multipart, run:

cargo add axum --features multipart

Cargo will merge this with any existing feature settings automatically. After changing Cargo.toml, run cargo build or cargo run again. Cargo will download the multer crate and compile it into your project. If you see no errors, the feature is enabled.

Everything Is Set Up:

If your build finishes without errors after adding the feature, the Multipart extractor is ready to use. You can confirm by typing axum::extract::Multipart somewhere in your code - if it compiles, the feature is working.

A Minimal Working Example

Let's build the smallest possible Axum application that receives a multipart request and does something with it. This will not be a full file-upload endpoint with disk storage; it will just print the fields to the terminal so you can see the extractor in action. Open your src/main.rs and replace its content with the following code. Make sure your Cargo.toml includes the multipart feature as shown above.

src/main.rs
use axum::{
    extract::Multipart,
    routing::post,
    Router,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/upload", post(handle_upload));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
async fn handle_upload(mut multipart: Multipart) {
    while let Some(field) = multipart.next_field().await.unwrap() {
        let name = field.name().unwrap_or("unnamed").to_string();
        let data = field.bytes().await.unwrap();
        println!(
            "Field name: {:?}, byte length: {}",
            name,
            data.len()
        );
    }
}

The handler takes mut multipart: Multipart as its only argument. The mut keyword is required because we will call next_field() on it repeatedly, and that method changes the internal position in the stream. Inside the loop, each call to next_field() returns an Option<Field>. When it returns None, there are no more fields and the loop ends. For each field, we read its name using field.name(), which returns Option<&str>. Then we read the entire content of the field into a Bytes object using field.bytes().await. Finally, we print the name and the length of the data.

This handler does not return anything meaningful - it implicitly returns (), which Axum converts into an empty 200 OK response. In a real application you would return a status code or a JSON acknowledgment, but for testing the extractor this is enough.

To test this endpoint, you need to send a multipart request. The easiest way is with curl. Open a second terminal while the server is running and execute:

curl -X POST http://127.0.0.1:3000/upload \
  -F "username=alice" \
  -F "note=hello there"

The -F flag tells curl to send a multipart/form-data request with the given fields. When you run this, your server terminal will print something like:

Field name: "username", byte length: 5
Field name: "note", byte length: 11

Fields arrive in the order they appear in the request body, which typically matches the order curl sends them.

Reading Files and Text Fields in the Same Request

The previous example treated every field as raw bytes, which works for both text and binary data. But often you want to distinguish between a text field like a username and a file field like an uploaded image. The Field type provides a file_name() method that returns Option<&str>. If the field has a filename, it is a file upload; if not, it is a regular text field. You can use that to handle each case differently.

Here is an expanded handler that saves uploaded files to a local directory and prints text fields to the terminal. This still keeps things simple, but it shows the real pattern you would use in a production endpoint.

src/main.rs
use axum::{
    extract::Multipart,
    routing::post,
    Router,
};
use tokio::fs;
use tokio::io::AsyncWriteExt;
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/upload", post(handle_upload));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
async fn handle_upload(mut multipart: Multipart) {
    // Make sure the uploads directory exists
    fs::create_dir_all("uploads").await.unwrap();
    while let Some(field) = multipart.next_field().await.unwrap() {
        let name = field.name().unwrap_or("unnamed").to_string();
        if let Some(filename) = field.file_name() {
            // This is a file field. Save it to disk.
            let filepath = format!("uploads/{}", filename);
            let mut file = fs::File::create(&filepath).await.unwrap();
            let data = field.bytes().await.unwrap();
            file.write_all(&data).await.unwrap();
            println!("Saved file '{}' ({} bytes)", filepath, data.len());
        } else {
            // This is a regular text field. Print it.
            let data = field.bytes().await.unwrap();
            let text = String::from_utf8_lossy(&data);
            println!("Text field '{}' = '{}'", name, text);
        }
    }
}

This version introduces a few new things. First, we ensure an uploads directory exists using tokio::fs::create_dir_all. Then, for each field, we check field.file_name(). If it is Some(filename), we create a new file inside the uploads directory with that name, read all bytes from the field, and write them to the file. If there is no filename, we treat the field as text and convert its bytes into a String using String::from_utf8_lossy, which replaces invalid UTF-8 sequences with a placeholder character. This is safe to call on arbitrary bytes because it never panics on invalid input.

To test this, use curl with a real file. Create a small text file first:

echo "This is the content of my file" > sample.txt
curl -X POST http://127.0.0.1:3000/upload \
  -F "username=alice" \
  -F "avatar=@sample.txt"

The server will create uploads/sample.txt containing the same content and print both the text field and the file field information.

Never trust the uploaded filename as a path:

The filename comes from the client, so a request can send a name like ../../etc/passwd or an absolute path. Building a file path with format!("uploads/{}", filename) would then write outside your uploads directory. Before using the filename, check that it contains no /, \, or .. segments, or replace it with a name your server generates itself and keep the original name only as a label in your response.

Memory Usage with Large Files:

In both examples above, we used field.bytes().await to load the entire field content into memory before processing it. For small files this is fine, but for large video or archive uploads this can consume hundreds of megabytes of RAM per request. The Field type also provides a chunk() method that returns a stream of smaller pieces. For production endpoints that accept large files, you should stream each chunk directly to disk instead of calling bytes(). The important thing now is to remember that bytes() is convenient but not always the right tool.

Understanding the Multipart Extractor Internals

When you put Multipart as a handler parameter, Axum's extractor system looks at the incoming request's Content-Type header. If the header starts with multipart/form-data, Axum constructs a Multipart instance by handing the raw request body to the multer parser. If the Content-Type header is missing or is something else, like application/json, the extractor will reject the request and Axum returns an error response (by default a 400 Bad Request). That means you cannot accidentally pass a JSON body to a handler that expects Multipart and have it silently parse incorrectly.

The Multipart struct itself is a thin wrapper around a stream of fields. Its most important method is next_field(), which returns a future that resolves to Option<Field>. You call it repeatedly until you get None. Each Field contains the part's headers and a body stream. You can read the field's name with name(), its filename with file_name(), its content type with content_type(), and its data either all at once with bytes() or incrementally with chunk().

Axum limits the size of the whole multipart request body to 2 megabytes by default. This is axum's DefaultBodyLimit, not a per-field limit inside the multer parser: the limit applies to the entire body stream, and it is enforced while your handler reads the fields. If the body is larger than the limit, next_field() (or bytes() on a field) returns an error. You can raise the limit for a route or for the whole router with the DefaultBodyLimit layer:

use axum::{extract::{DefaultBodyLimit, Multipart}, routing::post, Router};

let app = Router::new()
    .route("/upload", post(handle_upload))
    .layer(DefaultBodyLimit::max(10 * 1024 * 1024)); // allow bodies up to 10 MB

How that error reaches the client depends on your handler. If the handler returns a Result whose error type is MultipartError, axum turns the over-limit error into a 413 Payload Too Large response with the body "Request payload is too large". The type lives at axum::extract::multipart::MultipartError - it is not re-exported at axum::extract, so import it from the multipart module. Here is the same upload handler rewritten to return that Result instead of unwrapping:

src/main.rs
use axum::{
    extract::{multipart::MultipartError, DefaultBodyLimit, Multipart},
    routing::post,
    Router,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/upload", post(handle_upload))
        .layer(DefaultBodyLimit::max(10 * 1024 * 1024)); // allow bodies up to 10 MB
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
async fn handle_upload(mut multipart: Multipart) -> Result<String, MultipartError> {
    let mut total = 0;
    while let Some(field) = multipart.next_field().await? {
        let data = field.bytes().await?;
        total += data.len();
    }
    Ok(format!("Received {} bytes", total))
}

The ? after next_field().await and field.bytes().await passes any MultipartError straight out of the handler, and axum converts it into a response. Without the DefaultBodyLimit layer - with the default 2 MB limit in place - uploading a 3 MB file gets back 413 Payload Too Large with the body Request payload is too large. With the 10 MB limit shown above, the same 3 MB upload succeeds and the handler reports the byte count. A wrong Content-Type, on the other hand, gives a 400 Bad Request with the body "Invalid boundary for multipart/form-data request". But the examples earlier on this page call .unwrap() on the result of next_field(), so with those examples an over-limit upload panics the handler task instead of producing a clean response. For a production endpoint, return the Result rather than unwrapping.

Forgetting the Feature Flag:

The most common beginner mistake is writing a handler with Multipart and then seeing a compilation error that says something like "failed to resolve: use of undeclared crate or module extract" or "cannot find type Multipart in module extract". This almost always means you forgot to add features = ["multipart"] to your axum dependency. Double-check your Cargo.toml before spending time debugging the handler code.

Alternative Ways to Handle Multipart Data

Axum's built-in Multipart extractor is the standard way and works well for most cases. But the ecosystem offers other approaches. One popular crate is axum_typed_multipart, which provides a type-safe layer on top of the same underlying multer parsing. Instead of manually calling next_field() and handling each field dynamically, you define a Rust struct with fields that have attributes describing which multipart fields they map to. The crate then derives the parsing logic automatically.

For example, with axum_typed_multipart, you might write something like this:

use axum_typed_multipart::{TryFromMultipart, TypedMultipart};
#[derive(TryFromMultipart)]
struct UploadData {
    username: String,
    avatar: axum::body::Bytes,
}
async fn handle_upload(
    TypedMultipart(data): TypedMultipart<UploadData>,
) {
    println!("Username: {}", data.username);
    println!("Avatar size: {} bytes", data.avatar.len());
}

This crate is not part of the Axum core and must be added as a separate dependency - for axum 0.8, use axum_typed_multipart = "0.17" in your Cargo.toml. It can reduce boilerplate when your multipart structure is fixed and known ahead of time. However, it adds an external dependency, and the dynamic approach with Multipart remains more flexible for cases where the field names are not known at compile time. For learning purposes, it is best to first understand the built-in extractor, then explore typed alternatives if they fit your project.

Comparing multipart with json and form Features

Axum provides several feature flags for different body formats, and it is easy to mix them up. The multipart feature is specifically for multipart/form-data bodies, which are used for file uploads and mixed content. The json feature enables the Json extractor for application/json bodies. The form feature enables the Form extractor for application/x-www-form-urlencoded bodies, which are the kind sent by traditional HTML forms without files. These three formats are mutually exclusive in a request: a single request cannot be both JSON and multipart at the same time. You enable the features that match the request types your endpoints need to accept.

A common confusion is thinking that Form can handle file uploads. It cannot, because application/x-www-form-urlencoded only supports text; binary data must be base64-encoded by the client, which is inefficient and not supported by standard HTML file inputs. So if you need to accept files, you must use multipart and not form.

FeatureRequest Content-TypeTypical Use Case
multipartmultipart/form-dataFile uploads, mixed text and binary data
jsonapplication/jsonREST APIs exchanging structured data
formapplication/x-www-form-urlencodedSimple HTML forms without files

Common Mistakes and How to Avoid Them

Beyond forgetting the feature flag itself, several other pitfalls catch new Axum developers. The first is trying to use serde deserialization directly on multipart data. Multipart is not JSON; you cannot derive Deserialize and expect Axum to magically parse it. You must manually iterate over fields and parse each one as needed.

Another mistake is forgetting that next_field() returns an Option and attempting to call .unwrap() on it directly without checking for None. The correct pattern is a while let Some(field) = ... loop, not a for loop or a single call. If your handler only expects one file, you might be tempted to call next_field() once and ignore the rest, but that discards the remainder of the upload the client already sent. Always drain the entire stream, even if you don't use every field.

A subtler issue is that field.name() and field.file_name() return Option<&str>, and the strings they reference are owned by the field object. If you try to store those references after the field is dropped, you'll get a borrow checker error. Convert them to owned String values if you need to keep them.

Finally, remember that the default size limit is 2 megabytes for the whole request body, not per field. If a user uploads a file larger than that, reading the fields returns an error - and with the .unwrap() calls used in the examples above, that error panics the handler. For production applications, return a Result from the handler instead of unwrapping, and raise the limit with a DefaultBodyLimit layer when you genuinely need larger uploads.

Multipart and Middleware:

Middleware that inspects the request body, such as logging or authentication layers that read the entire body, can interfere with multipart parsing. The Multipart extractor expects to consume the raw request body stream. If another layer has already buffered or altered that stream, the extractor may fail. This is a more advanced concern, but if you see weird errors when using multipart alongside certain middleware, check the order in which your layers are applied.

Step-by-Step Integration into an Existing Project

If you already have a working Axum project and want to add multipart support, follow this ordered sequence. Each step depends on the previous one being complete.

1

Step 1: Add the multipart feature to Cargo.toml

Open your Cargo.toml and locate the axum dependency. Add "multipart" to the features list. If there is no features list yet, create one. The line should look like:

Cargo.toml
axum = { version = "0.8", features = ["multipart"] }

Save the file.

2

Step 2: Run cargo build to download multer

In your terminal, run:

cargo build

Cargo will fetch the multer crate and any of its dependencies, then compile everything. If you see errors about missing types, double-check the feature spelling. The feature name is exactly multipart, all lowercase.

3

Step 3: Add a route and handler that uses Multipart

Open src/main.rs and add a new route, for example .route("/upload", post(handle_upload)). Then write the handler function that takes Multipart as a parameter and iterates over fields. Use the minimal example from earlier as a starting point.

4

Step 4: Run the server and send a test request

Start the server with cargo run, then in another terminal send a multipart request with curl:

curl -X POST http://127.0.0.1:3000/upload \
  -F "test_field=hello"

If everything works, your server terminal prints the field name and length. If you get a compilation error, revisit step 1.

Summary

The multipart feature flag is the switch that brings multipart parsing into your Axum application. It pulls in the multer crate and exposes the Multipart extractor, which you use as a handler parameter to receive file uploads and mixed-form data. Without this feature, the extractor does not exist and your code will not compile. Enabling it is a one-line change in Cargo.toml, and the extractor itself is straightforward to use: call next_field() in a loop, check whether each field is a file or text, and read the data either all at once with bytes() or incrementally with chunk().

The key insight to carry forward is that Axum's modular feature system keeps your binary small and focused. You only include parsing logic for the request formats your application actually needs. Now that you understand how to enable and use multipart, you are ready to build real file-upload endpoints, handle large files with streaming, and configure size limits appropriately. Those topics build directly on the foundation you have just laid here.