expression

Axum: read a multipart text field

A multipart form carries named parts separated by a boundary. This handler accepts a single title and reads it as text. It uses a small total request budget and rejects absent, unknown or additional fields. In-memory standalone Cargo example. Expected stdout (not executed): 200 Notes Common mistake: Trying to extract Multipart after another extractor has already consumed the request body.

Formal Syntax & Structure

rust syntaxrust
multipart.next_field().await?; field.text().await?

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{extract::Multipart, routing::post, http::header};    async fn upload(mut form: Multipart) -> Result<String, StatusCode> {        let field = form.next_field().await.map_err(|e| e.status())?.ok_or(StatusCode::BAD_REQUEST)?;        if field.name() != Some("title") { return Err(StatusCode::BAD_REQUEST); }        let title = field.text().await.map_err(|e| e.status())?;        if form.next_field().await.map_err(|e| e.status())?.is_some() { return Err(StatusCode::BAD_REQUEST); }        Ok(title)    }    let app = Router::new().route("/upload", post(upload)) .layer(axum::extract::DefaultBodyLimit::max(1024));    let req = Request::builder().method("POST").uri("/upload")        .header(header::CONTENT_TYPE, "multipart/form-data; boundary=demo")        .body(Body::from("--demo\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nNotes\r\n--demo--\r\n")).unwrap();    let r = app.oneshot(req).await.unwrap();    println!("{}", r.status().as_u16());    let b = to_bytes(r.into_body(), 256).await.unwrap();    if !b.is_empty() { println!("{}", String::from_utf8_lossy(&b)); }}
Rust Reference