Learn Axum · 10/13

Files & Static Assets

7 min read

Files & Static Assets: The Digital Logistics of Axum

Welcome back, code traveler! 🚀 You’ve mastered routing and JSON, which is great if you are building a text-based adventure game from 1980. But in the modern web, people want stuff. They want images of cats, CSS files to make things pretty, and they want to upload profile pictures that are suspiciously high-resolution.

Today, we are turning your Axum server into a digital warehouse. We will learn how to serve files, accept deliveries (uploads), and hand out packages (downloads).


1. Serving Static Directories: Setting up ServeDir

The Problem

You have a folder called assets containing style.css, logo.png, and script.js.
Without a dedicated tool, you would have to write a specific route for every single file:
route("/style.css", get(return_css))
route("/logo.png", get(return_logo))

This is tedious. It's like working at a library and having to memorize the text of every book to recite it when someone asks.

The Solution: ServeDir

We want to tell Axum: "If anyone asks for something under the path /static, just look inside my computer's assets folder and give them what they find."

Axum is very modular. It doesn't actually know how to read files from the disk out of the box. It delegates this to a dedicated crate called tower-http.

🛠️ Industry Setup

First, we need the fs (filesystem) feature from tower-http.

Terminal:

bash
cargo add axum tokio --features tokio/full
cargo add tower-http --features fs

The Code

Here is how you mount a physical directory to a URL path.

rust
use axum::{Router, routing::get};
use tower_http::services::ServeDir;
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    // 1. Define where your files live locally
    // "assets" is a folder next to your Cargo.toml
    let assets_dir = ServeDir::new("assets");

    let app = Router::new()
        .route("/", get(|| async { "Hello, World!" }))
        // 2. Nest the service. 
        // Any request to /static/foo.png will look for assets/foo.png
        .nest_service("/assets", assets_dir);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    println!("Server running on http://localhost:3000");
    println!("Try accessing http://localhost:3000/assets/style.css");
    
    axum::serve(listener, app).await.unwrap();
}

🧠 Under the Hood

When a request hits /assets, tower-http checks if the file exists.

  1. If yes: It streams the file bytes and automatically sets the correct Content-Type (e.g., text/css or image/png).
  2. If no: It returns a 404.

Fun Fact: The first image ever uploaded to the web was a photo of a parody pop band formed by employees at CERN called "Les Horribles Cernettes".


2. Multipart Forms: Accepting File Uploads

The Problem

JSON bodies are great for text data ({"name": "Alice"}). But files are binary data. Trying to stuff a binary image into a JSON string requires Base64 encoding, which increases the file size by ~33% and burns CPU.

The Solution: multipart/form-data

This is a standard encoding that allows a browser to send different "parts" in one request. One part could be a text field (username), and another part could be the raw binary bytes of an image.

Axum Tool: Multipart

Axum provides an extractor called Multipart to handle this stream.

The Code

We will create a handler that inspects what is being uploaded.

rust
use axum::{
    extract::Multipart,
    response::Html,
    routing::{get, post},
    Router,
};

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(show_form))
        .route("/upload", post(upload_file));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

// A simple HTML form to test uploads
async fn show_form() -> Html<&'static str> {
    Html(r#"
        <!doctype html>
        <html>
            <head></head>
            <body>
                <form action="/upload" method="post" enctype="multipart/form-data">
                    <label>
                        Upload file:
                        <input type="file" name="file" multiple>
                    </label>
                    <input type="submit" value="Upload">
                </form>
            </body>
        </html>
    "#)
}

// The Handler
async fn upload_file(mut multipart: Multipart) {
    // We iterate over the "parts" of the form
    while let Some(field) = multipart.next_field().await.unwrap() {
        let name = field.name().unwrap().to_string();
        let file_name = field.file_name().unwrap_or("unknown").to_string();
        let content_type = field.content_type().unwrap_or("text/plain").to_string();
        
        // This parses the entire field into memory (Careful! See Section 3)
        let data = field.bytes().await.unwrap();

        println!(
            "Length of `{}` (`{}`): {} bytes",
            name,
            file_name,
            data.len()
        );
    }
}

3. Saving Files: Streaming Uploads Safely

The Problem

In the example above, we used field.bytes().await. This loads the entire file into RAM.
Imagine 100 users simultaneously upload 4GB video files. Your server's RAM will vanish faster than free pizza at a hackathon, and the Operating System will kill your application (OOM Kill).

The Solution: Streaming

We must read the file in small chunks (e.g., 8KB or 64KB) and write those chunks to the disk immediately. The entire file never exists in RAM all at once.

🛡️ Industry Standard Practices

  1. Never trust the user's filename. They might name a file ../../../../etc/passwd. Always generate a random ID (UUID) or sanitize the name.
  2. Stream, don't slurp.

The Code

We need tokio for async file operations.

rust
use axum::{extract::Multipart, response::IntoResponse, http::StatusCode};
use tokio::fs::File;
use tokio::io::AsyncWriteExt; // Trait for write_all
use uuid::Uuid; 

// Handler: Streaming to Disk
async fn save_file(mut multipart: Multipart) -> impl IntoResponse {
    while let Some(mut field) = multipart.next_field().await.unwrap() {
        
        // 1. Generate a safe filename
        // We look for extension, or default to .bin
        let file_name = field.file_name().unwrap_or("data.bin");
        let extension = std::path::Path::new(file_name)
            .extension()
            .and_then(std::ffi::OsStr::to_str)
            .unwrap_or("bin");
            
        // Create a unique name: e.g., "uploads/550e8400-e29b....png"
        let new_filename = format!("{}.{}", Uuid::new_v4(), extension);
        let path = std::path::Path::new("uploads").join(new_filename);

        // 2. Create the file on disk
        // Ensure the "uploads" directory exists before running this!
        let mut file = match File::create(&path).await {
            Ok(f) => f,
            Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("File error: {}", e)).into_response()
        };

        // 3. Stream the chunks
        while let Ok(Some(chunk)) = field.chunk().await {
            if let Err(e) = file.write_all(&chunk).await {
                return (StatusCode::INTERNAL_SERVER_ERROR, format!("Write error: {}", e)).into_response();
            }
        }
    }

    (StatusCode::OK, "Upload complete").into_response()
}

Imagination time: Think of streaming like a bucket brigade fighting a fire. You don't wait to fill a swimming pool before throwing it on the fire. You pass small buckets continuously. It's efficient and doesn't require a swimming-pool-sized person to hold it.


4. Returning Files: Sending Files as Download Responses

The Problem

If you just read a file and send the bytes, the browser might try to display it as text, or it might render the image. Sometimes, you want to force the user to download the file (e.g., generating a PDF invoice).

The Solution

We need to set HTTP Headers:

  1. Content-Type: Tells the browser what the file is.
  2. Content-Disposition: Tells the browser to "attachment" (download) rather than "inline" (show).

We also want to stream the file from the disk to the network, rather than loading it all into memory first.

The Code

We will use axum::body::Body to create a stream from a tokio::fs::File.

Additional Dependency:
cargo add tokio-util --features io (Required to turn a File into a Stream).

rust
use axum::{
    body::Body,
    http::{header, StatusCode},
    response::{IntoResponse, Response},
};
use tokio::fs::File;
use tokio_util::io::ReaderStream;

async fn download_file() -> impl IntoResponse {
    let filename = "uploads/report.pdf";

    // 1. Open the file asynchronously
    let file = match File::open(filename).await {
        Ok(file) => file,
        Err(_) => return (StatusCode::NOT_FOUND, "File not found").into_response(),
    };

    // 2. Convert the file into a Stream of bytes
    let stream = ReaderStream::new(file);
    // Convert the stream into an Axum Body
    let body = Body::from_stream(stream);

    // 3. Build the response with headers
    Response::builder()
        .header(header::CONTENT_TYPE, "application/pdf")
        .header(
            header::CONTENT_DISPOSITION,
            "attachment; filename=\"monthly_report.pdf\"",
        )
        .body(body)
        .unwrap()
}

🧠 Under the Hood (Optimization)

By using Body::from_stream, Axum and Tokio efficiently handle backpressure. If the user's internet is slow, the server pauses reading from the disk. This ensures your server stays responsive even if 1000 users with dial-up internet try to download 4K movies simultaneously.


Summary Checklist 📝

  1. ServeDir: Use tower-http to serve static assets (CSS/JS).
  2. Multipart: Use axum::extract::Multipart for uploads.
  3. Streaming Write: Use field.chunk() and tokio::fs::File to save uploads without eating RAM.
  4. Streaming Read: Use ReaderStream and Body::from_stream to send downloads efficiently.

Now go forth and build the next great file-sharing empire! (Just make sure you have enough hard drive space). 📦


References & Further Reading 🔗

Challenge

Write a JavaScript function named fizzBuzz that takes a single positive integer argument, n.

The function must generate a sequence from 1 up to and including n. For each number in the sequence, apply the following rules:

  1. If the number is divisible by both 3 and 5, replace it with the string "FizzBuzz".
  2. If the number is divisible by 3, replace it with the string "Fizz".
  3. If the number is divisible by 5, replace it with the string "Buzz".
  4. If the number is not divisible by 3 or 5, it should remain as is, but converted to a string.

Your function should return an array of strings containing the final results in order.

Expected result

The function should return an array of strings. For example, calling fizzBuzz(16) should produce the following output:

json
[
  "1",
  "2",
  "Fizz",
  "4",
  "Buzz",
  "Fizz",
  "7",
  "8",
  "Fizz",
  "Buzz",
  "11",
  "Fizz",
  "13",
  "14",
  "FizzBuzz",
  "16"
]
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.