expression

Axum: count uploaded bytes incrementally

Read one part in chunks and track the running total. Enforce a per-file budget independently of the overall multipart budget, which also includes boundaries and headers. Chunk sizes are not assumed. This example discards data instead of persisting an incomplete upload. In-memory standalone Cargo example. Expected stdout (not executed): 200 5 Common mistake: Checking only the size of each chunk, not the accumulated file size.

Formal Syntax & Structure

rust syntaxrust
while let Some(chunk) = field.chunk().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 mut field = form.next_field().await.map_err(|e| e.status())?.ok_or(StatusCode::BAD_REQUEST)?;        if field.name() != Some("document") { return Err(StatusCode::BAD_REQUEST); }        let mut total = 0usize;        while let Some(chunk) = field.chunk().await.map_err(|e| e.status())? {            total = total.checked_add(chunk.len()).ok_or(StatusCode::PAYLOAD_TOO_LARGE)?;            if total > 5 { return Err(StatusCode::PAYLOAD_TOO_LARGE); }        }        if form.next_field().await.map_err(|e| e.status())?.is_some() { return Err(StatusCode::BAD_REQUEST); }        Ok(total.to_string())    }    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=\"document\"; filename=\"notes.txt\"\r\nContent-Type: text/plain\r\n\r\nhello\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