Avatar upload route

Learn how to build a complete avatar upload route in Axum that accepts one PNG or JPEG image, enforces a 1 MB size limit, and answers every failure with the app JSON error shape

An avatar upload is the first complete upload feature most apps need. A user picks a picture, the browser sends it, and the server answers with either an acceptance or a clear reason for the refusal. This page builds that route from the pieces of the earlier pages: the loop that reads the fields, the file name that tells a file from a text field, the content type that gives a first check, the size limit that caps the body, and the app's own error shape for every failure.

Where This Fits

Everything before this page was one idea at a time. This page puts them together into a route a real app could ship. The route accepts one image field named avatar, allows PNG and JPEG only, caps the upload at 1 megabyte, and answers every outcome, success or failure, in the same JSON shape. The file is validated and reported, not saved to disk. Saving the bytes is the work of the next group of pages, and this page stops at the point where the upload has been checked and accepted.

Think of the route as a reception desk with a checklist. A visitor arrives with a parcel. The desk checks that there is a parcel at all, then that the label says it is a picture, then that it fits through the door. Each check has its own answer when it fails, and only a parcel that passes all three gets a receipt. The desk does not open the parcel and frame the picture. That is a later job. It only decides whether the parcel is acceptable.

The Smallest Working Version

The route has three files. The error type lives in src/errors.rs, the route lives in src/lib.rs, and the server startup lives in src/main.rs. The error type is the app's shared one, with the same variants and messages used everywhere else in this app:

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum AppError {
    #[error("resource not found")]
    NotFound,
    #[error("{0}")]
    ValidationError(String),
    #[error("something went wrong")]
    InternalError,
    #[error("unauthorized")]
    Unauthorized,
    #[error("forbidden")]
    Forbidden,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
            AppError::ValidationError(message) => {
                (StatusCode::UNPROCESSABLE_ENTITY, message)
            }
            AppError::InternalError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "something went wrong".to_string(),
            ),
            AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
            AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

The route itself reads the fields, finds the file, checks its label, reads its bytes, and answers with a JSON report:

src/lib.rs
pub mod errors;

use axum::{
    extract::{multipart::MultipartError, DefaultBodyLimit, Multipart},
    response::{IntoResponse, Response},
    routing::post,
    Json, Router,
};
use errors::AppError;
use serde_json::{json, Value};

fn multipart_error_response(err: MultipartError) -> Response {
    (err.status(), Json(json!({ "error": err.body_text() }))).into_response()
}

async fn avatar(mut multipart: Multipart) -> Result<Json<Value>, Response> {
    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(multipart_error_response)?
    {
        let Some(file_name) = field.file_name().map(|s| s.to_string()) else {
            let _data = field.bytes().await.map_err(multipart_error_response)?;
            continue;
        };
        if file_name.trim().is_empty() {
            let _data = field.bytes().await.map_err(multipart_error_response)?;
            continue;
        }
        let content_type = field.content_type().unwrap_or("").to_string();
        if content_type != "image/png" && content_type != "image/jpeg" {
            return Err(AppError::ValidationError(
                "avatar must be a PNG or JPEG image".to_string(),
            )
            .into_response());
        }
        let data = field
            .bytes()
            .await
            .map_err(multipart_error_response)?;
        return Ok(Json(json!({
            "file_name": file_name,
            "content_type": content_type,
            "size": data.len(),
        })));
    }
    Err(AppError::ValidationError("no file was uploaded".to_string()).into_response())
}

pub fn app() -> Router {
    let avatar_routes = Router::new()
        .route("/avatar", post(avatar))
        .layer(DefaultBodyLimit::max(1024 * 1024));
    Router::new().merge(avatar_routes)
}

The size limit is a layer on the avatar routes, set to 1 megabyte. It is attached to the small router that holds the route, not to the whole app, so other routes keep the default limit. The main.rs is the familiar startup:

src/main.rs
use upload_demo::app;

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app()).await.unwrap();
}

The Cargo.toml needs the multipart feature, plus serde, serde_json, and thiserror for the error type:

Cargo.toml
[package]
name = "upload-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = { version = "0.8", features = ["multipart"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"

Run the server with cargo run, then send a small PNG file:

curl -X POST http://127.0.0.1:3000/avatar \
  -F "avatar=@photo.png;type=image/png"

The response is status 200 with this body:

{"content_type":"image/png","file_name":"photo.png","size":12}

A live run of this exact route returned that response for a 12 byte file sent as image/png. The route accepted the upload and reported what it received. It did not save the file anywhere. The response is the receipt, and the saving comes later.

A 200 with the file name means the route works:

If a small PNG returns 200 with its file name, content type, and size, the route is wired up correctly. The loop found the file, the type check passed, the size limit allowed it, and the JSON report came back. That one response proves the whole route.

The Four Steps of the Route

The handler runs four steps in order, and each step depends on the one before it. The order is fixed, because a later step cannot run until the earlier one has succeeded.

1

Step 1: Find the file field

Loop through the fields and skip any field without a file name. A text field is skipped, and a file field with an empty name is skipped too. If the loop ends without finding a file, answer with 422 and the message no file was uploaded.

let Some(file_name) = field.file_name().map(|s| s.to_string()) else {
    let _data = field.bytes().await.map_err(multipart_error_response)?;
    continue;
};
if file_name.trim().is_empty() {
    let _data = field.bytes().await.map_err(multipart_error_response)?;
    continue;
}
2

Step 2: Check the content type

Read the field's content type and compare it against the two accepted values. Anything else is rejected at once with 422 and the message avatar must be a PNG or JPEG image. The field's bytes are not read yet, so a rejected file costs the server nothing.

let content_type = field.content_type().unwrap_or("").to_string();
if content_type != "image/png" && content_type != "image/jpeg" {
    return Err(AppError::ValidationError(
        "avatar must be a PNG or JPEG image".to_string(),
    )
    .into_response());
}
3

Step 3: Read the bytes

Read the field with bytes(). The 1 megabyte limit is enforced during this read, so an oversized file fails here with a 413, not after it has been loaded. The error helper turns that failure into the JSON error shape.

let data = field
    .bytes()
    .await
    .map_err(multipart_error_response)?;
4

Step 4: Answer with the report

Return the file name, the content type, and the size as JSON with status 200. The handler returns at once, without reading any further fields, because the route accepts exactly one avatar.

return Ok(Json(json!({
    "file_name": file_name,
    "content_type": content_type,
    "size": data.len(),
})));

The step order matters. The type check runs before the bytes are read, so a wrong file type is rejected without loading anything. The size limit runs during the read, so an oversized file fails while it is still arriving. A handler that read the bytes first and checked the type afterwards would do the expensive work before the cheap rejection, which is the wrong way round.

Every Failure, and Its Answer

The route has four failures, and each one has a distinct status and message. The table lists them all, and the curl commands below each one show the live response.

SituationStatusBody
Small PNG or JPEG200{"content_type":"image/png","file_name":"photo.png","size":12}
Wrong content type, such as text/plain422{"error":"avatar must be a PNG or JPEG image"}
No file field at all422{"error":"no file was uploaded"}
File over the 1 MB limit413{"error":"Request payload is too large"}

Send a text file as the avatar:

curl -X POST http://127.0.0.1:3000/avatar \
  -F "avatar=@notes.txt;type=text/plain"

The response is status 422 with {"error":"avatar must be a PNG or JPEG image"}. A live run returned exactly that.

Send only a text field, with no file at all:

curl -X POST http://127.0.0.1:3000/avatar \
  -F "username=nitiksh"

The response is status 422 with {"error":"no file was uploaded"}. A live run returned exactly that.

Send a 3 megabyte PNG, which is over the 1 megabyte limit:

python3 -c "open('/tmp/big.png','wb').write(b'x'*3000000)"
curl -X POST http://127.0.0.1:3000/avatar \
  -F "avatar=@/tmp/big.png;type=image/png"

The response is status 413 with {"error":"Request payload is too large"}. A live run returned exactly that. The 413 comes from the multipart error's own status and message, wrapped in the app's JSON shape by the helper. The handler never held the 3 megabytes, because the read failed at the limit.

All four responses share the same shape. A success is a JSON object with the upload's details. A failure is a JSON object with a single error key. A client can handle every outcome with one piece of parsing code, checking the status first and then reading either the details or the message.

Why the Handler Returns Response as Its Error

The handler's return type is Result<Json<Value>, Response>, which looks unusual next to the other handlers in this app, which return Result<Json<Value>, AppError>. The reason is that this handler has two kinds of error, and they need different handling.

The validation errors, the wrong type and the missing file, are AppError::ValidationError values, and they convert into responses through the IntoResponse implementation in errors.rs. The multipart errors, the oversized read and the damaged body, already carry their own status and message, and wrapping them in AppError would throw that information away. The Response error type lets the handler return both kinds directly: an AppError converted with .into_response(), and a multipart error converted with the helper.

The map_err(multipart_error_response)? calls are where the second kind is handled. Each read that can fail is mapped through the helper, which builds a response with the error's own status and its own message inside the {"error": "..."} shape. The ? then returns that response from the handler early, so the rest of the handler never runs.

Two error kinds, one error type:

Validation errors come from the app's rules, and multipart errors come from the read itself. Returning Response as the error type lets the handler answer with both, without converting one kind into the other and losing what it knew.

Why the Limit Is a Layer, Not a Check

The 1 megabyte cap is enforced by DefaultBodyLimit::max(1024 * 1024) layered on the avatar routes. It is not enforced by checking data.len() after bytes() returns, and the difference matters.

A check after the read happens too late. By the time bytes() returns, the whole file is already in memory, which is the outcome the limit exists to prevent. A 3 gigabyte upload would be fully read before the check rejected it, and the server would have held 3 gigabytes for no reason. The layer stops the read at 1 megabyte, so the handler never holds more than the limit allows.

There is a second reason. The layer is attached to the router, so it applies to the route no matter how the handler changes. A future version of the handler that reads the field with chunk() instead of bytes() is still capped, because the cap is on the body stream, not on one reading method. A size check inside the handler would have to be rewritten for every new reading method, and forgotten once.

A manual size check still has a place, as a friendlier second opinion. A handler can compare data.len() against the limit after the read and return a message written for its own route, such as avatar must be smaller than 1 MB. With the layer in place, that check never triggers, because the layer fires first. Without the layer, the check is the only protection, and it runs too late to save the memory. The layer is the protection. The manual check is only a message.

The HTML Form That Sends the Avatar

A browser sends the avatar with a file input inside a form. The form needs method="post" and enctype="multipart/form-data", which is the attribute that makes the browser send the body in the multipart format. Without it, the browser sends the fields as a plain form body, and the extractor rejects the request with a 400.

<form method="post" action="/avatar" enctype="multipart/form-data">
  <input type="file" name="avatar" accept="image/png, image/jpeg" />
  <button type="submit">Upload avatar</button>
</form>

The name="avatar" attribute is what makes the field's name avatar, which is the name the handler looks for. The accept attribute tells the browser's file picker to show image files, but it is only a hint for the picker. It does not stop a user from picking another kind of file, and it does not change what the server checks. The server still validates the content type, because the browser's hint is not enforcement.

A form can also carry text fields alongside the file, such as a display name. The handler skips those fields in step 1, reading and discarding their bytes, and only the avatar field is checked. The loop must still visit them, because the fields arrive in a stream and the next one cannot be read until the current one is finished.

A Variation With a Manual Size Check

Some routes need a size message written for that route, rather than the multipart error's generic text. The variation below keeps the layer as the real cap and adds a manual check after the read, so the message can name the route's own limit. The check is written to return a 413, because an oversized upload is a payload problem, not a validation problem:

src/lib.rs
const MAX_AVATAR_BYTES: usize = 1024 * 1024;

async fn avatar(mut multipart: Multipart) -> Result<Json<Value>, Response> {
    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(multipart_error_response)?
    {
        let Some(file_name) = field.file_name().map(|s| s.to_string()) else {
            let _data = field.bytes().await.map_err(multipart_error_response)?;
            continue;
        };
        if file_name.trim().is_empty() {
            let _data = field.bytes().await.map_err(multipart_error_response)?;
            continue;
        }
        let content_type = field.content_type().unwrap_or("").to_string();
        if content_type != "image/png" && content_type != "image/jpeg" {
            return Err(AppError::ValidationError(
                "avatar must be a PNG or JPEG image".to_string(),
            )
            .into_response());
        }
        let data = field
            .bytes()
            .await
            .map_err(multipart_error_response)?;
        if data.len() > MAX_AVATAR_BYTES {
            return Err((
                StatusCode::PAYLOAD_TOO_LARGE,
                Json(json!({ "error": "avatar must be smaller than 1 MB" })),
            )
                .into_response());
        }
        return Ok(Json(json!({
            "file_name": file_name,
            "content_type": content_type,
            "size": data.len(),
        })));
    }
    Err(AppError::ValidationError("no file was uploaded".to_string()).into_response())
}

This variation needs StatusCode imported from axum::http. With the 1 megabyte layer in place, the manual check never fires, because the read fails first. The variation is only useful when the route's own message matters more than the generic one, and the layer is still what enforces the cap. A route that drops the layer and keeps only this check has no real protection, and that trade is not worth the friendlier message.

A manual size check is a message, not a limit:

Checking data.len() after bytes() returns runs after the whole file is in memory. It can improve the error message, but it cannot protect the server. Keep the layer as the cap, and treat the manual check as wording only.

Common Beginner Mistakes

Returning the first field without checking it

// Wrong - accepts text fields as avatars
while let Some(field) = multipart.next_field().await.unwrap() {
    let data = field.bytes().await.unwrap();
    return Json(json!({ "size": data.len() }));
}

The first field in the request might be a text field, not the file. The handler must check file_name() on each field and skip the ones that are not files, as step 1 does. Returning the first field's bytes accepts whatever arrived first, which is whatever the client sent first.

Checking the size after reading the bytes

Shown above as the variation, and worth repeating as a mistake when it stands alone. A handler that only checks data.len() after bytes() has no limit during the read. The layer is the limit. The check is only a message.

Trusting the file name as the stored name

The handler reports the client file name in its response, and that is all it does with it. Using it as a disk path would let a crafted name escape the upload folder, as the page on file names shows. The avatar route does not save the file at all, so the name never becomes a path here. When saving is added later, the stored name must be generated on the server.

Accepting the content type as proof

The route checks the label and rejects a wrong one, but it does not verify the bytes are really a PNG or a JPEG. A file labelled image/png can hold anything, and this route would accept it. That is a known limit of this page, not an oversight. Verifying the bytes is the work of the validation pages that follow, and this route is the first gate, not the last one.

Forgetting the layer on the route

The limit is attached to the avatar routes with .layer(DefaultBodyLimit::max(1024 * 1024)). A route built without that layer falls back to the default 2 megabyte cap, so a 1.5 megabyte avatar would be accepted even though the route's own rule says 1 megabyte. The limit lives on the router, so a new route added to a different router does not inherit it. Check that the layer call wraps the route it is meant to protect.

The label check is not a file check:

A file labelled image/png can hold any bytes at all, and this route accepts it on the strength of the label. Do not serve the bytes as an image, or pass them to an image library, without checking them first. The validation pages cover that check.

Testing the Avatar Route

A test that sends a PNG field and checks the report comes back proves the happy path without a running server. The body helper from the earlier pages is reused here, with the same fixed boundary:

tests/avatar_test.rs
use axum::{
    body::Body,
    extract::{DefaultBodyLimit, Multipart},
    http::{Request, StatusCode},
    routing::post,
    Json, Router,
};
use serde_json::json;
use tower::ServiceExt;

fn multipart_body(boundary: &str, parts: &[(&str, Option<&str>, Option<&str>, &[u8])]) -> Vec<u8> {
    let mut body = Vec::new();
    for (name, file_name, content_type, data) in parts {
        body.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
        let mut disposition = format!("Content-Disposition: form-data; name=\"{name}\"");
        if let Some(file_name) = file_name {
            disposition.push_str(&format!("; filename=\"{file_name}\""));
        }
        body.extend_from_slice(disposition.as_bytes());
        body.extend_from_slice(b"\r\n");
        if let Some(content_type) = content_type {
            body.extend_from_slice(format!("Content-Type: {content_type}\r\n").as_bytes());
        }
        body.extend_from_slice(b"\r\n");
        body.extend_from_slice(data);
        body.extend_from_slice(b"\r\n");
    }
    body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
    body
}

#[tokio::test]
async fn avatar_accepts_a_small_png() {
    let app = Router::new()
        .route(
            "/avatar",
            post(|mut multipart: Multipart| async move {
                while let Some(field) = multipart.next_field().await.unwrap() {
                    let Some(file_name) = field.file_name().map(|s| s.to_string()) else {
                        let _ = field.bytes().await.unwrap();
                        continue;
                    };
                    let content_type = field.content_type().unwrap_or("").to_string();
                    let data = field.bytes().await.unwrap();
                    return Json(json!({
                        "file_name": file_name,
                        "content_type": content_type,
                        "size": data.len(),
                    }));
                }
                Json(json!({ "error": "no file was uploaded" }))
            }),
        )
        .layer(DefaultBodyLimit::max(1024 * 1024));
    let body = multipart_body(
        "test-boundary",
        &[(
            "avatar",
            Some("photo.png"),
            Some("image/png"),
            b"fake-png-bytes",
        )],
    );
    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/avatar")
                .header(
                    "Content-Type",
                    "multipart/form-data; boundary=test-boundary",
                )
                .body(Body::from(body))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(
        serde_json::from_slice::<serde_json::Value>(&bytes).unwrap(),
        json!({
            "file_name": "photo.png",
            "content_type": "image/png",
            "size": 14,
        })
    );
}

Run it with cargo test. It passes when the small PNG returns 200 with its file name, content type, and size. The test uses unwrap() inside the handler, which is acceptable in a test, because the test's own assertions are what catch a failure. A second test in the same file can send a text/plain field and expect a 422, and a third can send a body over the limit and expect a 413. The same three cases are the ones the curl commands above check by hand.

Final Complete Example

Here is the whole page in one place, the error type, the route, the startup, and the dependencies:

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum AppError {
    #[error("resource not found")]
    NotFound,
    #[error("{0}")]
    ValidationError(String),
    #[error("something went wrong")]
    InternalError,
    #[error("unauthorized")]
    Unauthorized,
    #[error("forbidden")]
    Forbidden,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
            AppError::ValidationError(message) => {
                (StatusCode::UNPROCESSABLE_ENTITY, message)
            }
            AppError::InternalError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "something went wrong".to_string(),
            ),
            AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
            AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}
src/lib.rs
pub mod errors;

use axum::{
    extract::{multipart::MultipartError, DefaultBodyLimit, Multipart},
    response::{IntoResponse, Response},
    routing::post,
    Json, Router,
};
use errors::AppError;
use serde_json::{json, Value};

fn multipart_error_response(err: MultipartError) -> Response {
    (err.status(), Json(json!({ "error": err.body_text() }))).into_response()
}

async fn avatar(mut multipart: Multipart) -> Result<Json<Value>, Response> {
    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(multipart_error_response)?
    {
        let Some(file_name) = field.file_name().map(|s| s.to_string()) else {
            let _data = field.bytes().await.map_err(multipart_error_response)?;
            continue;
        };
        if file_name.trim().is_empty() {
            let _data = field.bytes().await.map_err(multipart_error_response)?;
            continue;
        }
        let content_type = field.content_type().unwrap_or("").to_string();
        if content_type != "image/png" && content_type != "image/jpeg" {
            return Err(AppError::ValidationError(
                "avatar must be a PNG or JPEG image".to_string(),
            )
            .into_response());
        }
        let data = field
            .bytes()
            .await
            .map_err(multipart_error_response)?;
        return Ok(Json(json!({
            "file_name": file_name,
            "content_type": content_type,
            "size": data.len(),
        })));
    }
    Err(AppError::ValidationError("no file was uploaded".to_string()).into_response())
}

pub fn app() -> Router {
    let avatar_routes = Router::new()
        .route("/avatar", post(avatar))
        .layer(DefaultBodyLimit::max(1024 * 1024));
    Router::new().merge(avatar_routes)
}
src/main.rs
use upload_demo::app;

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app()).await.unwrap();
}
Cargo.toml
[package]
name = "upload-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = { version = "0.8", features = ["multipart"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"

Run it and try the four requests from the table. A small PNG returns 200 with its report. A text file returns 422 with the image message. A text-only request returns 422 with the missing-file message. A 3 megabyte PNG returns 413 with the too-large message. All four were observed live against this shape of route, and all four share the same JSON error shape on the failure side.

Summary

The avatar route is the first place where the upload ideas stop being separate lessons and start being one feature, and the shape of that feature is a checklist with a distinct answer for each failure. The loop finds the file, the label check rejects the wrong kind before any bytes are read, the layer caps the body while it is still arriving, and every outcome comes back in one JSON shape. The important decision in the whole route is not any single check. It is the order of the checks, cheap before expensive, label before bytes, limit during the read rather than after it, because that order is what keeps a bad upload cheap for the server. The route also draws a clear line around what it does not do. It does not save the file, it does not verify the bytes are really an image, and it does not trust the file name as a path. Each of those is a separate job with its own page, and the route is built so each one can be added without changing the checks that are already there.