1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
//! Run with
//!
//! ```not_rust
//! cd examples && cargo run -p example-multipart-form
//! ```
use axum::{
extract::{DefaultBodyLimit, Multipart},
response::Html,
routing::get,
Router,
};
use std::net::SocketAddr;
use tower_http::limit::RequestBodyLimitLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_multipart_form=debug,tower_http=debug".into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
// build our application with some routes
let app = Router::new()
.route("/", get(show_form).post(accept_form))
.layer(DefaultBodyLimit::disable())
.layer(RequestBodyLimitLayer::new(
250 * 1024 * 1024, /* 250mb */
))
.layer(tower_http::trace::TraceLayer::new_for_http());
// run it with hyper
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn show_form() -> Html<&'static str> {
Html(
r#"
<!doctype html>
<html>
<head></head>
<body>
<form action="/" method="post" enctype="multipart/form-data">
<label>
Upload file:
<input type="file" name="file" multiple>
</label>
<input type="submit" value="Upload files">
</form>
</body>
</html>
"#,
)
}
async fn accept_form(mut multipart: Multipart) {
while let Some(field) = multipart.next_field().await.unwrap() {
let name = field.name().unwrap().to_string();
let file_name = field.file_name().unwrap().to_string();
let content_type = field.content_type().unwrap().to_string();
let data = field.bytes().await.unwrap();
println!(
"Length of `{}` (`{}`: `{}`) is {} bytes",
name,
file_name,
content_type,
data.len()
);
}
}
|