Answer#
A browser sends a form with files as multipart/form-data: one part per field, with a boundary line between parts. Multipart walks over the parts.
use axum::{
body::{to_bytes, Body},
extract::{DefaultBodyLimit, Multipart},
http::{header, Request, StatusCode},
routing::post,
Router,
};
use tower::ServiceExt;
async fn upload(mut form: Multipart) -> Result<String, (StatusCode, String)> {
let mut report = Vec::new();
while let Some(field) = form.next_field().await.map_err(|e| (e.status(), e.body_text()))? {
let name = field.name().unwrap_or("?").to_string();
let file_name = field.file_name().map(str::to_string);
let bytes = field.bytes().await.map_err(|e| (e.status(), e.body_text()))?;
report.push(format!("{name}: file={file_name:?} {} bytes", bytes.len()));
}
Ok(report.join("\n"))
}
fn multipart_body(boundary: &str, file_len: usize) -> Body {
let mut s = format!("--{boundary}\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nHoliday\r\n");
s += &format!("--{boundary}\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"a.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n");
s += &"x".repeat(file_len);
s += &format!("\r\n--{boundary}--\r\n");
Body::from(s)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/upload", post(upload)).layer(DefaultBodyLimit::max(10_000)); // the default limit is 2 MB
for len in [500, 20_000] {
let req = Request::post("/upload")
.header(header::CONTENT_TYPE, "multipart/form-data; boundary=XYZ")
.body(multipart_body("XYZ", len)).unwrap();
let res = app.clone().oneshot(req).await.unwrap();
let status = res.status().as_u16();
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("file of {len} bytes -> {status}\n{}", String::from_utf8_lossy(&body));
}
}file of 500 bytes -> 200
title: file=None 7 bytes
photo: file=Some("a.jpg") 500 bytes
file of 20000 bytes -> 413
Request payload is too large- The text field
titlehas no file name; the file fieldphotohasa.jpg. - The file of 500 bytes was accepted. The one of 20,000 bytes went over the 10,000 byte limit of
DefaultBodyLimit, and the request was refused with 413. field.bytes()loads the whole part into memory. For big files read the field in chunks (field.chunk()) and write each chunk to disk.
axum = { version = "0.8.9", features = ["multipart"] }Common mistakes#
- Using the client's
file_nameto build a path on disk. It can contain..or a drive letter. Generate your own name (a random id) and keep the original only as text. - Trusting the
Content-Typethe client claims for the part. Check the real content if the type matters. - Leaving the size limit at its default without knowing it. The documentation gives 2 MB for
Multipart; state your own limit in the code.
Related questions#
How do I limit the number of files?#
Count the fields in the loop and return an error status when the count is too high.
Sources#
- axum,
Multipart: https://docs.rs/axum/0.8.9/axum/extract/struct.Multipart.html (read 2026-12-05) - axum,
DefaultBodyLimit: https://docs.rs/axum/0.8.9/axum/extract/struct.DefaultBodyLimit.html (read 2026-12-05)