How to Handle File Uploads in Rust Web Applications
Use the multipart crate to parse incoming multipart/form-data requests and extract files in your Axum or Actix-web handler. Add the dependency to Cargo.toml and implement a handler that consumes the stream to save the file.
use axum::{extract::Multipart, response::IntoResponse, routing::post, Router};
use std::io::Write;
#[tokio::main]
async fn main() {
let app = Router::new().route("/upload", post(upload));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn upload(mut multipart: Multipart) -> impl IntoResponse {
while let Some(field) = multipart.next_field().await.unwrap() {
let mut file = std::fs::File::create("uploaded.txt").unwrap();
while let Some(chunk) = field.chunk().await.unwrap() {
file.write_all(&chunk).unwrap();
}
}
"File uploaded"
}