Field iteration in multipart uploads
Learn how next_field reads one field at a time from a multipart upload, what it returns when the fields run out, and how to tell text fields apart from file fields
A multipart body is not one value. It is a list of fields, sent one after another, and the server reads them in the order the client sent them. The Multipart extractor does not hand you that list all at once. It hands you one field at a time, through a method called next_field(), and you call it in a loop until it tells you there are no more fields. That loop is the core of every upload handler, and this page is about how it works.
Where This Fits
The previous page ended with the extractor ready and the handler about to run. This page is the first thing the handler does. The loop here reads each field and its bytes, and it is the same loop every later page builds on. The name, the file name, and the content type of each field are read inside this loop, and each of those gets its own page next.
Think of a multipart body as a stack of envelopes passed through a slot, one at a time. next_field() takes the next envelope off the stack. When the stack is empty, it says so, and the loop stops. You never see the whole stack at once, and you never need to. One envelope at a time is enough, because each one is handled the same way.
The Smallest Working Version
The loop has one shape, and it appears in every upload handler on this track:
use axum::{extract::Multipart, routing::post, Json, Router};
use serde_json::{json, Value};
async fn upload(mut multipart: Multipart) -> Json<Value> {
let mut fields = Vec::new();
while let Some(field) = multipart.next_field().await.unwrap() {
let name = field.name().map(|s| s.to_string());
let data = field.bytes().await.unwrap();
fields.push(json!({
"name": name,
"size": data.len(),
}));
}
Json(json!({ "fields": fields }))
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/upload", post(upload));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The Cargo.toml is the same as the earlier pages:
[package]
name = "upload-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8", features = ["multipart"] }
tokio = { version = "1", features = ["full"] }
serde_json = "1"
Run the server, then send a request with two fields:
curl -X POST http://127.0.0.1:3000/upload \
-F "username=nitiksh" \
-F "avatar=@photo.png;type=image/png"
The server answers with status 200 and this body:
{"fields":[{"name":"username","size":7},{"name":"avatar","size":12}]}
A live run of this exact program returned that response for a text field holding nitiksh and a 12 byte file. The loop ran twice, once per field, and stopped on its own when the fields ran out.
Two fields in, two entries out:
If the two-field request returns two entries in the same order the fields were sent, the loop works. The order is the client's order, and the count matches the number of fields in the request. That response is the check for this page.
The Loop, Piece by Piece
The loop is short, but every part of it earns its place. Here is the line again:
while let Some(field) = multipart.next_field().await.unwrap() {
next_field() is an async method, which is why .await follows it. Async means the call can pause while it waits for the next piece of the body to arrive over the network, and resume when the bytes are there. The method returns a Result, a Rust type that holds either a success value or an error. The success value is an Option, a type that holds either a value, written Some(field), or nothing at all, written None.
while let Some(field) = ... is the pattern that drives the loop. It takes the success value out of the Result, and if that value is Some(field), it runs the loop body with the field bound to the name field. If the value is None, the loop ends. The .unwrap() in the middle turns a Result into its success value directly, and crashes the handler with a panic if the Result holds an error instead. These examples use unwrap() to keep the code short. A real handler replaces it with proper error handling, and the later pages show how.
The two possible outcomes of next_field() are the whole story of the loop:
- It returns
Ok(Some(field))when another field is ready. The loop body runs. - It returns
Ok(None)when the fields are exhausted. The loop ends, and the code after it runs.
There is a third outcome, Err, when reading fails. That happens when the body is cut off mid-field, when the size limit is hit, or when the multipart data itself is malformed. The error type is MultipartError, and the pages on size limits and the avatar route show what to do with it. For now, the point is that the loop has exactly two ways to end: the fields run out, which is normal, or a read fails, which is an error.
What a Field Is
Each value the loop hands you is a Field. A field is one part of the multipart body, and it carries four things. The first is its name, the name attribute from the form, such as username or avatar. The second is its file name, present only when the field holds a file. The third is its content type, such as image/png, present only when the client sent one. The fourth is its data, the bytes of the field itself.
The smallest example reads two of those four. field.name() returns the name, and field.bytes() returns the data. Both return types that need a small explanation. name() returns an Option<&str>, which is Some("username") when the field has a name and None when it does not. The .map(|s| s.to_string()) call turns that borrowed string into an owned String so it can be stored in the response. bytes() is async and returns a Result<Bytes, MultipartError>, where Bytes is a type that holds a chunk of raw bytes, and .len() gives its size.
A field's data is read exactly once. Calling bytes() a second time on the same field returns empty data, because the first call already consumed it. The field is a stream that can only be read forward, and there is no way to rewind it. If a handler needs the data twice, it must keep the Bytes value from the first read and reuse that.
Text Fields and File Fields
A multipart body mixes two kinds of field, and the loop sees both without distinction. A text field carries a short value typed into a form, like a username. A file field carries the contents of a file. The difference between them is in the attributes, not in the reading code. Both are read with the same next_field() and bytes() calls.
The live run from the smallest example shows the difference. The text field answered with a name of username, a size of 7, and no file name and no content type. The file field answered with a name of avatar, a size of 12, a file name of photo.png, and a content type of image/png. The text field's missing file name and content type are not errors. A text field simply does not have them, and the methods return None for it. The next two pages take the file name and the content type apart in detail.
Here is the same handler extended to report all four attributes, so the difference is visible in one response:
use axum::{extract::Multipart, routing::post, Json, Router};
use serde_json::{json, Value};
async fn upload(mut multipart: Multipart) -> Json<Value> {
let mut fields = Vec::new();
while let Some(field) = multipart.next_field().await.unwrap() {
let name = field.name().map(|s| s.to_string());
let file_name = field.file_name().map(|s| s.to_string());
let content_type = field.content_type().map(|s| s.to_string());
let data = field.bytes().await.unwrap();
fields.push(json!({
"name": name,
"file_name": file_name,
"content_type": content_type,
"size": data.len(),
}));
}
Json(json!({ "fields": fields }))
}
Sending the same two-field request now returns:
{"fields":[{"name":"username","file_name":null,"content_type":null,"size":7},{"name":"avatar","file_name":"photo.png","content_type":"image/png","size":12}]}
That response was observed live. The null values are JSON's way of writing Rust's None. A field with no file name is not a broken field. It is a text field, and null is the correct answer for it.
Skipping Fields You Do Not Want
A handler does not have to use every field. The loop still has to visit each one, because the fields arrive in a stream and the next one cannot be read until the current one is finished. Skipping a field means reading it and throwing the result away, not ignoring it entirely.
This handler only keeps the field named avatar and drops the rest:
use axum::{extract::Multipart, routing::post, Json, Router};
use serde_json::{json, Value};
async fn upload(mut multipart: Multipart) -> Json<Value> {
let mut found = None;
while let Some(field) = multipart.next_field().await.unwrap() {
if field.name() == Some("avatar") {
let data = field.bytes().await.unwrap();
found = Some(data.len());
} else {
let _data = field.bytes().await.unwrap();
}
}
Json(json!({ "avatar_size": found }))
}
The else branch reads the unwanted field's bytes and throws them away. That read is what moves the stream past the field so the next call to next_field() can return the field after it. Without it, the loop would stop at the first unwanted field, because the parser cannot skip ahead on its own. The response for the two-field request is {"avatar_size": 12}.
A beginner mistake is to break out of the loop after finding the wanted field, or to return early. That works for the response, but it leaves the rest of the request body unread. The client may still be sending data, and the connection ends while the upload is half finished. Reading every field to the end, even the ones you discard, is the tidy way to finish a request.
Read every field, even the ones you throw away:
The fields arrive in a stream, and the parser cannot jump past one without reading it. A handler that stops early leaves the rest of the body unread. Always drain the loop to the end, reading the bytes of unwanted fields and discarding them.
The Order Fields Arrive In
Fields arrive in the order the client sent them, and the loop returns them in that order. The curl command above sends username first and avatar second, and the response lists them in that order. A browser form sends its fields in the order they appear in the form. A handler that depends on the order, for example one that expects the text fields before the file, is depending on the client to send them that way, and a client is free to send them in any order.
The safe habit is to treat the fields as an unordered set. Collect what you need as the loop runs, and decide what to do with it after the loop ends. The avatar route on a later page does exactly that, gathering the file field whenever it appears and answering only after the loop has finished.
When the Loop Ends Early With an Error
The loop ends normally when next_field() returns None. It ends with an error when the body is damaged. The most common damage is a body that stops in the middle of a field, which happens when the client disconnects or the size limit is crossed. In that case next_field() returns an Err, and the unwrap() in these examples panics. A panic inside a handler crashes the request with a 500 status, and it also drops the connection without a useful message for the client.
The fix is to replace unwrap() with error handling that turns the MultipartError into a response. The shape of that fix is a small helper that keeps the error's own status code and message:
use axum::{
extract::{multipart::MultipartError, Multipart},
http::StatusCode,
response::{IntoResponse, Response},
routing::post,
Json, Router,
};
use serde_json::{json, Value};
fn multipart_error_response(err: MultipartError) -> Response {
(err.status(), Json(json!({ "error": err.body_text() }))).into_response()
}
async fn upload(mut multipart: Multipart) -> Result<Json<Value>, Response> {
let mut fields = Vec::new();
while let Some(field) = multipart
.next_field()
.await
.map_err(multipart_error_response)?
{
let name = field.name().map(|s| s.to_string());
let data = field
.bytes()
.await
.map_err(multipart_error_response)?;
fields.push(json!({
"name": name,
"size": data.len(),
}));
}
Ok(Json(json!({ "fields": fields })))
}
map_err converts the error inside the Result into a Response, and the ? returns that response from the handler early. The helper uses the error's own status() and body_text() methods, so a size-limit failure becomes a 413 with the message Request payload is too large, and a malformed body becomes a 400 with a message describing the problem. Both were observed live. The MultipartError type lives at axum::extract::multipart::MultipartError, which is worth knowing because the docs do not always spell out the full path.
This handler returns Result<Json<Value>, Response>, which is the return type that lets a handler answer with either a success value or a ready-made response. The error arm carries a Response rather than the app's AppError type, because the multipart error already knows its own status and message, and wrapping it in AppError would throw that information away. The pages on size limits and the avatar route build on this helper.
MultipartError already knows its status:
A MultipartError carries two methods, status() and body_text(), that give the right HTTP status and the right message for the failure. Use them instead of guessing the status yourself. A size-limit error reports 413, and a malformed body reports 400.
A Plain Text Diagram of the Loop
The whole flow fits in a short diagram:
Request body arrives as a stream of fields
|
v
next_field() -> Some(field) -> read name, bytes -> loop again
|
v
next_field() -> None -> fields are exhausted -> loop ends
|
v
next_field() -> Err -> read failed -> return an error response
Each call to next_field() advances the stream by one field. The loop body runs once per field, and the code after the loop runs once, after the last field. Nothing about the loop needs to know how many fields there are in advance, because the None at the end is what stops it.
Common Beginner Mistakes
Calling next_field once and expecting all the fields
// Wrong - only the first field is ever read
let field = multipart.next_field().await.unwrap();
One call returns one field. Every field after the first stays unread, and the handler answers as if the upload held a single field. The loop is not optional. It is the mechanism that reads the rest.
Forgetting that bytes() can only be called once per field
// Wrong - the second read finds nothing left
let first = field.bytes().await.unwrap();
let second = field.bytes().await.unwrap();
The first bytes() call consumes the field's data. The second call returns an empty value, not the data again. Keep the result of the first call in a variable and use that variable everywhere the data is needed.
Returning early from inside the loop
// Wrong - the remaining fields are never read
while let Some(field) = multipart.next_field().await.unwrap() {
if field.name() == Some("avatar") {
let data = field.bytes().await.unwrap();
return Json(json!({ "size": data.len() }));
}
}
The response is correct, but the request body is left half unread. Collect the answer in a variable, let the loop finish, and return after it. The avatar route on a later page shows that shape with a full example.
Using unwrap in a real handler
Every unwrap() in these examples is a teaching shortcut. In a real handler, a failed read panics the request and returns a bare 500 with no message. Replace the unwrap() calls with the map_err helper shown above, or with the app's error type, so a damaged upload gets a proper error response instead of a crash.
Do not ship unwrap on next_field or bytes:
unwrap() on a field read turns any damaged upload into a panic and a bare 500. A client that disconnects mid-upload, or a body that crosses the size limit, triggers it. Handle the MultipartError and return its status and message instead.
Testing the Loop
A test that sends a two-field body through the router and checks the names come back in order proves the loop works without a running server. The body is built by hand, with a fixed boundary string and each field written out as text:
use axum::{
body::Body,
extract::Multipart,
http::{Request, StatusCode},
routing::post,
Json, Router,
};
use serde_json::json;
use tower::ServiceExt;
fn multipart_body(boundary: &str, parts: &[(&str, Option<&str>, Option<&str>, &[u8])]) -> Vec<u8> {
let mut body = Vec::new();
for (name, file_name, content_type, data) in parts {
body.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
let mut disposition = format!("Content-Disposition: form-data; name=\"{name}\"");
if let Some(file_name) = file_name {
disposition.push_str(&format!("; filename=\"{file_name}\""));
}
body.extend_from_slice(disposition.as_bytes());
body.extend_from_slice(b"\r\n");
if let Some(content_type) = content_type {
body.extend_from_slice(format!("Content-Type: {content_type}\r\n").as_bytes());
}
body.extend_from_slice(b"\r\n");
body.extend_from_slice(data);
body.extend_from_slice(b"\r\n");
}
body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
body
}
#[tokio::test]
async fn upload_returns_field_names_in_order() {
let app = Router::new().route(
"/upload",
post(|mut multipart: Multipart| async move {
let mut names = Vec::new();
while let Some(field) = multipart.next_field().await.unwrap() {
names.push(field.name().unwrap().to_string());
let _ = field.bytes().await.unwrap();
}
Json(json!({ "names": names }))
}),
);
let body = multipart_body(
"test-boundary",
&[
("username", None, None, b"nitiksh"),
(
"avatar",
Some("photo.png"),
Some("image/png"),
b"fake-png-bytes",
),
],
);
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/upload")
.header(
"Content-Type",
"multipart/form-data; boundary=test-boundary",
)
.body(Body::from(body))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&bytes).unwrap(),
json!({ "names": ["username", "avatar"] })
);
}
The helper builds each part from four pieces, the field name, an optional file name, an optional content type, and the raw bytes. The \r\n sequences are the line endings the multipart format requires, carriage return followed by line feed. The test needs tower as a dev dependency, as on the previous page. A live run of this test passed, returning the two names in order.
Final Complete Example
Here is the whole page in one program, the field reporter with the error helper, the field skipper, and the route:
use axum::{
extract::{multipart::MultipartError, Multipart},
response::{IntoResponse, Response},
routing::post,
Json, Router,
};
use serde_json::{json, Value};
fn multipart_error_response(err: MultipartError) -> Response {
(err.status(), Json(json!({ "error": err.body_text() }))).into_response()
}
async fn upload(mut multipart: Multipart) -> Result<Json<Value>, Response> {
let mut fields = Vec::new();
while let Some(field) = multipart
.next_field()
.await
.map_err(multipart_error_response)?
{
let name = field.name().map(|s| s.to_string());
let file_name = field.file_name().map(|s| s.to_string());
let content_type = field.content_type().map(|s| s.to_string());
let data = field
.bytes()
.await
.map_err(multipart_error_response)?;
fields.push(json!({
"name": name,
"file_name": file_name,
"content_type": content_type,
"size": data.len(),
}));
}
Ok(Json(json!({ "fields": fields })))
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/upload", post(upload));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run it and send the two-field request from the smallest example. The response lists both fields with their names, file names, content types, and sizes, in the order they were sent. Send a request with a single text field and the response holds one entry with null for the file name and the content type. Send an empty multipart body and the response holds an empty list, because the first next_field() call returns None at once. Each of those three responses was observed live against this shape of handler.
Summary
The loop is the one pattern that every upload handler shares, and its shape never changes: call next_field(), handle the field, repeat until None. The interesting decisions all sit inside that loop, which fields to keep, which to discard, and how to answer when a read fails. The loop itself stays dumb on purpose. It does not know how many fields are coming, it does not care whether a field is text or a file, and it stops by itself when the stream ends. That simplicity is what makes it reliable, and it is also what makes the next two pages possible. Each of them reads one more attribute off the field the loop just handed over, the file name and the content type, and neither of them changes the loop at all.