Can the framework handle multiple files? #2634
-
Description
Docs from Golang : https://pkg.go.dev/mime/multipart
Here's my code in Rust:
How can I loop with multiple file input ? Environment:
Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Of course. Here's a fully working application: use rocket::fs::TempFile;
use rocket::response::content::RawHtml;
use rocket::form::Form;
#[get("/")]
fn upload_page() -> RawHtml<&'static str> {
RawHtml(r#"
<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload Example</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<label for="files">Select files:</label>
<input type="file" id="files" name="[]" multiple><br><br>
<input type="submit">
</form>
</body>
</html>
"#)
}
#[post("/", data = "<files>")]
fn upload_post(files: Form<Vec<TempFile<'_>>>) -> String {
let files = files.into_inner();
for (i, file) in files.iter().enumerate() {
println!("{i}: {}", file.len());
}
format!("{} files received", files.len())
}
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/upload", routes![upload_page, upload_post])
} You probably want to actually name the field something, in which case you'd use a struct: #[derive(FromForm)]
struct Upload<'r> {
files: Vec<TempFile<'r>>,
} Then you can name the form field It doesn't have to use |
Beta Was this translation helpful? Give feedback.
-
We can't possibly enumerate every possibility for forms, but the forms guide is rather comprehensive: https://rocket.rs/v0.5-rc/guide/requests/#forms, and the forms example illustrated several uses of |
Beta Was this translation helpful? Give feedback.
Of course. Here's a fully working application: