expression
Axum: multipart field metadata
A file part exposes optional field name, original filename and declared media type. These are client-supplied metadata, not trusted evidence of the bytes or a safe storage path. This inspection-only handler discards the data and returns a fixed summary of the metadata checks. In-memory standalone Cargo example. Expected stdout (not executed): 200 metadata matches: true; bytes: 5 Common mistake: Using a supplied filename as a disk path or trusting the Content-Type as proof of format.
Formal Syntax & Structure
rust syntaxrust
field.name(); field.file_name(); field.content_type()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)?; let matches = field.name() == Some("document") && field.file_name().is_some() && field.content_type() == Some("text/plain"); let bytes = field.bytes().await.map_err(|e| e.status())?; Ok(format!("metadata matches: {matches}; bytes: {}", bytes.len())) } 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)); }}