Skip to main content

Module upload

Module upload 

Source
Expand description

Bounded multipart uploads, with files written to temporary files.

Axum’s Multipart reads parts as they arrive and leaves the limits to the service. read holds every part to Limits: how many parts, how large each text field and each file, how much text is held in memory, and how large all of it. Text fields are kept in memory, and each file goes to a temporary file that is deleted when its File is dropped, so a large upload costs disk, not memory.

use axa::{Result, format, upload::{self, Limits}};
use axum::extract::Multipart;

async fn avatar(multipart: Multipart) -> Result<axum::response::Response> {
    let limits = Limits {
        file_bytes: 2_000_000,
        files: 1,
        accept: Some(vec!["image/png", "image/jpeg"]),
        ..Limits::default()
    };
    let upload = upload::read(multipart, &limits).await?;
    let Some(file) = upload.files.first() else {
        return axa::prelude::bad_request("send one image");
    };
    // `file.path()` is the temporary file, which is deleted when `upload` drops:
    // copy or persist it first.
    format::json(serde_json::json!({ "name": file.file_name, "bytes": file.size }))
}

A part’s names and content type are the caller’s text, and no problem quotes them. A file name is cleaned with format::clean_file_name before anything sees it.

Structs§

File
A file, in a temporary file deleted when this drops.
Limits
How much an upload may hold. Every limit counts bytes as they arrive, so a caller that sends more is refused when it passes the limit, not after.
Text
A text field.
Upload
An upload’s parts, in the order they came.

Functions§

read
Read every part of multipart, holding each to limits.