Rust File Upload with Axum

Handle multipart file uploads in Rust using Axum with size limits, content type validation, streaming to disk, and async file operations using tokio for.

RustFile Upload

Code

snippet
use axum::{
  extract::Multipart,
  response::Json,
};
use serde_json::{json, Value};

async fn upload(mut multipart: Multipart) -> Json<Value> {
  while let Some(field) = multipart.next_field().await.unwrap() {
    let name = field.file_name().unwrap_or("unknown").to_string();
    let data = field.bytes().await.unwrap();
    if data.len() > 10 * 1024 * 1024 {
      return Json(json!({"error": "File too large"}));
    }
    tokio::fs::write(format!("uploads/{name}"), data).await.unwrap();
  }
  Json(json!({"status": "ok"}))
}

How the snippet works

Structurally, expect the function upload and nothing else.

Iteration happens inside while let Some(field) = multipart.next_field().await.unwrap() — everything outside it runs once.

Caveats

  • Plan for an install step: axum:: and serde_json:: are a real dependency, resolved by the package manager.

Applying it

The primary signature is fn upload(mut multipart: Multipart) -> Json<Value>

Import upload from the file and call it — the rest of the code is implementation detail.

Statements that matter

tokio::fs::write(format!("uploads/{name}"), data).await.unwrap();
let name = field.file_name().unwrap_or("unknown").to_string();
return Json(json!({"error": "File too large"}));

FAQ

Which packages must be installed first?
Yes. The imports resolve to `axum::` and `serde_json::`, which the package manager must provide.