Ty Q.
Ty Q.

Reputation: 317

Rust Axum Multipart Length Limit Exceeded

Referenced Axum documentation: docs.rs


Hello all, I am trying to create a simple file upload using HTML5 forms and Rust Axum.

The issue is that, while any normal file works, larger files (particularly video files) which I want to upload are too large. Axum (subsequently Tokio) panics because the Field size is too large for the file upload.

I can't seem to find any helpful information about either expanding the stream limit.

<form action="/upload" method="POST" enctype="multipart/form-data">
    <input type="file" name="filename" accept="video/mp4">
    <input type="submit" value="Upload video">
</form>
async fn upload(mut multipart: Multipart) {
    while let Some(mut field) = multipart.next_field().await.unwrap() {
        let name = field.name().unwrap().to_string();
        let data = field.bytes().await.unwrap();

        println!("Length of `{}` is {} bytes", name, data.len());
    }
}
thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: MultipartError { source: failed to read stream: failed to read stream: length limit exceeded }', src/main.rs:84:40
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: MultipartError { source: failed to read stream: failed to read stream: length limit exceeded }', src/main.rs:84:40
thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: MultipartError { source: failed to read stream: failed to read stream: length limit exceeded }', src/main.rs:84:40

To not take away from the primary part of this code, I have omitted the router, but its application is: .route("/upload", post(upload)) as per the example shown in the Axum documentation.

Quick note: to enable Multipart file uploads, you must add the Cargo feature flag "multipart" with Axum.

Any help is appreciated. Thank you.

Upvotes: 4

Views: 3513

Answers (1)

StratusFearMe21
StratusFearMe21

Reputation: 76

Have you tried using Axum's DefaultBodyLimit service?

use axum::{
    Router,
    routing::post,
    body::Body,
    extract::{DefaultBodyLimit, RawBody},
    http::Request,
};

let app = Router::new()
    .route(
        "/",
        // even with `DefaultBodyLimit` the request body is still just `Body`
        post(|request: Request<Body>| async {}),
    )
    .layer(DefaultBodyLimit::max(1024));

I found this example here

Upvotes: 3

Related Questions