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

57 lines
1.8 KiB
Rust
Raw Normal View History

2018-06-08 06:34:14 +02:00
use std::io::Write;
use actix_multipart::Multipart;
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
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);
let mut f = std::fs::File::create(filepath).unwrap();
// Field in turn is stream of *Bytes* object
while let Some(chunk) = field.next().await {
let data = chunk.unwrap();
let mut pos = 0;
while pos < data.len() {
let bytes_written = f.write(&data[pos..])?;
pos += bytes_written;
}
}
}
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-03-29 21:43:03 +01:00
fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
std::fs::create_dir_all("./tmp").unwrap();
let ip = "0.0.0.0:3000";
2019-03-29 21:43:03 +01:00
HttpServer::new(|| {
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-03-29 21:43:03 +01:00
.run()
}