2020-01-23 02:16:08 +01:00
|
|
|
use actix_multipart::Multipart;
|
|
|
|
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
|
|
|
|
use async_std::prelude::*;
|
2020-03-22 00:31:45 +01:00
|
|
|
use futures::{StreamExt, TryStreamExt};
|
2020-01-23 02:16:08 +01:00
|
|
|
|
|
|
|
async fn save_file(mut payload: Multipart) -> Result<HttpResponse, Error> {
|
|
|
|
// iterate over multipart stream
|
2020-03-22 00:31:45 +01:00
|
|
|
while let Ok(Some(mut field)) = payload.try_next().await {
|
2020-01-23 02:16:08 +01:00
|
|
|
let content_type = field
|
|
|
|
.content_disposition()
|
|
|
|
.ok_or_else(|| actix_web::error::ParseError::Incomplete)?;
|
|
|
|
let filename = content_type
|
|
|
|
.get_filename()
|
|
|
|
.ok_or_else(|| actix_web::error::ParseError::Incomplete)?;
|
2020-05-19 06:48:49 +02:00
|
|
|
let filepath = format!("./tmp/{}", sanitize_filename::sanitize(&filename));
|
2020-01-23 02:16:08 +01:00
|
|
|
let mut f = async_std::fs::File::create(filepath).await?;
|
|
|
|
|
|
|
|
// Field in turn is stream of *Bytes* object
|
|
|
|
while let Some(chunk) = field.next().await {
|
|
|
|
let data = chunk.unwrap();
|
|
|
|
f.write_all(&data).await?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(HttpResponse::Ok().into())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn index() -> HttpResponse {
|
|
|
|
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"/>
|
|
|
|
<input type="submit" value="Submit"></button>
|
|
|
|
</form>
|
|
|
|
</body>
|
|
|
|
</html>"#;
|
|
|
|
|
|
|
|
HttpResponse::Ok().body(html)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[actix_rt::main]
|
|
|
|
async fn main() -> std::io::Result<()> {
|
|
|
|
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
|
|
|
|
async_std::fs::create_dir_all("./tmp").await?;
|
|
|
|
|
|
|
|
let ip = "0.0.0.0:3000";
|
|
|
|
|
|
|
|
HttpServer::new(|| {
|
|
|
|
App::new().wrap(middleware::Logger::default()).service(
|
|
|
|
web::resource("/")
|
|
|
|
.route(web::get().to(index))
|
|
|
|
.route(web::post().to(save_file)),
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.bind(ip)?
|
|
|
|
.run()
|
|
|
|
.await
|
|
|
|
}
|