2018-06-08 06:34:14 +02:00
|
|
|
use std::io::Write;
|
2019-12-07 15:40:31 +01:00
|
|
|
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">
|
2019-12-07 15:40:31 +01:00
|
|
|
<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)
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|
|
|
|
|
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");
|
2019-12-07 15:40:31 +01:00
|
|
|
std::fs::create_dir_all("./tmp").unwrap();
|
|
|
|
let ip = "0.0.0.0:3000";
|
2019-03-29 21:43:03 +01:00
|
|
|
HttpServer::new(|| {
|
2019-12-07 15:40:31 +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
|
|
|
})
|
2019-12-07 15:40:31 +01:00
|
|
|
.bind(ip)?
|
2019-03-29 21:43:03 +01:00
|
|
|
.run()
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|