actix-form-data/examples/simple.rs

57 lines
1.5 KiB
Rust
Raw Normal View History

2022-09-07 23:38:10 +00:00
use actix_form_data::{Error, Field, Form, FormData, Multipart, Value};
use actix_web::{
2020-06-06 02:40:44 +00:00
web::{post, resource},
2022-09-10 15:55:52 +00:00
App, HttpRequest, HttpResponse, HttpServer,
};
2021-09-06 00:37:13 +00:00
use futures_util::stream::StreamExt;
2022-09-07 23:38:10 +00:00
struct UploadedContent(Value<()>);
impl FormData for UploadedContent {
type Item = ();
type Error = Error;
2022-09-10 15:55:52 +00:00
fn form(_: &HttpRequest) -> Form<Self::Item, Self::Error> {
2022-09-07 23:38:10 +00:00
Form::new()
.field("Hey", Field::text())
.field(
"Hi",
Field::map()
.field("One", Field::int())
.field("Two", Field::float())
.finalize(),
)
.field(
"files",
Field::array(Field::file(|_, _, mut stream| async move {
while let Some(res) = stream.next().await {
res?;
}
Ok(()) as Result<(), Error>
})),
)
}
fn extract(value: Value<Self::Item>) -> Result<Self, Self::Error>
where
Self: Sized,
{
Ok(UploadedContent(value))
}
}
async fn upload(Multipart(UploadedContent(value)): Multipart<UploadedContent>) -> HttpResponse {
println!("Uploaded Content: {:#?}", value);
2020-06-06 02:40:44 +00:00
HttpResponse::Created().finish()
}
#[actix_rt::main]
async fn main() -> Result<(), anyhow::Error> {
2022-09-07 23:38:10 +00:00
HttpServer::new(move || App::new().service(resource("/upload").route(post().to(upload))))
.bind("127.0.0.1:8080")?
.run()
.await?;
Ok(())
}