FAQ - Help and questions

How do I accept file uploads in axum with Multipart?

#axum#multipart#uploads#securitypublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Enable the multipart feature, take a Multipart extractor and loop over next_field(); each field has a name, an optional file name and its bytes. Set a body size limit with DefaultBodyLimit, because uploads above it are refused with 413, and never use the client-sent file name as a path.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, Windows 11; the request bodies were built by hand and sent in-process

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A browser sends a form with files as multipart/form-data: one part per field, with a boundary line between parts. Multipart walks over the parts.

src/main.rsrust
use axum::{
    body::{to_bytes, Body},
    extract::{DefaultBodyLimit, Multipart},
    http::{header, Request, StatusCode},
    routing::post,
    Router,
};
use tower::ServiceExt;

async fn upload(mut form: Multipart) -> Result<String, (StatusCode, String)> {
    let mut report = Vec::new();
    while let Some(field) = form.next_field().await.map_err(|e| (e.status(), e.body_text()))? {
        let name = field.name().unwrap_or("?").to_string();
        let file_name = field.file_name().map(str::to_string);
        let bytes = field.bytes().await.map_err(|e| (e.status(), e.body_text()))?;
        report.push(format!("{name}: file={file_name:?} {} bytes", bytes.len()));
    }
    Ok(report.join("\n"))
}

fn multipart_body(boundary: &str, file_len: usize) -> Body {
    let mut s = format!("--{boundary}\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nHoliday\r\n");
    s += &format!("--{boundary}\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"a.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n");
    s += &"x".repeat(file_len);
    s += &format!("\r\n--{boundary}--\r\n");
    Body::from(s)
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/upload", post(upload)).layer(DefaultBodyLimit::max(10_000)); // the default limit is 2 MB
    for len in [500, 20_000] {
        let req = Request::post("/upload")
            .header(header::CONTENT_TYPE, "multipart/form-data; boundary=XYZ")
            .body(multipart_body("XYZ", len)).unwrap();
        let res = app.clone().oneshot(req).await.unwrap();
        let status = res.status().as_u16();
        let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        println!("file of {len} bytes -> {status}\n{}", String::from_utf8_lossy(&body));
    }
}
text
file of 500 bytes -> 200
title: file=None 7 bytes
photo: file=Some("a.jpg") 500 bytes
file of 20000 bytes -> 413
Request payload is too large
  • The text field title has no file name; the file field photo has a.jpg.
  • The file of 500 bytes was accepted. The one of 20,000 bytes went over the 10,000 byte limit of DefaultBodyLimit, and the request was refused with 413.
  • field.bytes() loads the whole part into memory. For big files read the field in chunks (field.chunk()) and write each chunk to disk.
Cargo.tomltoml
axum = { version = "0.8.9", features = ["multipart"] }

Common mistakes#

  • Using the client's file_name to build a path on disk. It can contain .. or a drive letter. Generate your own name (a random id) and keep the original only as text.
  • Trusting the Content-Type the client claims for the part. Check the real content if the type matters.
  • Leaving the size limit at its default without knowing it. The documentation gives 2 MB for Multipart; state your own limit in the code.

How do I limit the number of files?#

Count the fields in the loop and return an error status when the count is too high.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet