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.
Code
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"}))
}