1
0
mirror of https://github.com/actix/examples synced 2024-12-03 18:22:14 +01:00
examples/multipart/src/main.rs

60 lines
1.9 KiB
Rust
Raw Normal View History

2019-12-09 01:28:09 +01:00
use std::io::Write;
use actix_multipart::Multipart;
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
2019-12-07 18:59:24 +01:00
use futures::StreamExt;
async fn save_file(mut payload: Multipart) -> Result<HttpResponse, Error> {
// iterate over multipart stream
while let Some(item) = payload.next().await {
let mut field = item?;
let content_type = field.content_disposition().unwrap();
let filename = content_type.get_filename().unwrap();
let filepath = format!("./tmp/{}", filename);
2019-12-09 01:28:09 +01:00
// File::create is blocking operation, use threadpool
let mut f = web::block(|| std::fs::File::create(filepath))
.await
.unwrap();
// Field in turn is stream of *Bytes* object
while let Some(chunk) = field.next().await {
let data = chunk.unwrap();
2019-12-09 01:28:09 +01:00
// filesystem operations are blocking, we have to use threadpool
f = web::block(move || f.write_all(&data).map(|_| f)).await?;
}
}
Ok(HttpResponse::Ok().into())
2018-06-08 06:34:14 +02:00
}
2019-03-29 21:43:03 +01:00
fn index() -> HttpResponse {
2018-06-08 06:34:14 +02:00
let html = r#"<html>
<head><title>Upload Test</title></head>
<body>
<form target="/" method="post" enctype="multipart/form-data">
<input type="file" multiple name="file"/>
2018-06-08 06:34:14 +02:00
<input type="submit" value="Submit"></button>
</form>
</body>
</html>"#;
2019-03-29 21:43:03 +01:00
HttpResponse::Ok().body(html)
}
2019-12-07 18:59:24 +01:00
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
2019-03-29 21:43:03 +01:00
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
std::fs::create_dir_all("./tmp").unwrap();
2019-12-07 18:59:24 +01:00
let ip = "0.0.0.0:3000";
2019-12-07 18:59:24 +01:00
2019-03-29 21:43:03 +01:00
HttpServer::new(|| {
2019-12-07 18:59:24 +01:00
App::new().wrap(middleware::Logger::default()).service(
web::resource("/")
.route(web::get().to(index))
.route(web::post().to(save_file)),
)
2019-03-10 03:03:09 +01:00
})
.bind(ip)?
2019-12-07 18:59:24 +01:00
.start()
.await
}