Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::io::Write;
- use actix_web::{App, HttpResponse, HttpServer, middleware, web};
- use actix_multipart::Multipart;
- use actix_web::Error;
- use clap::Arg;
- use futures_lite::StreamExt;
- async fn save_file(mut payload: Multipart) -> Result<HttpResponse, Error> {
- while let Ok(Some(mut field)) = payload.try_next().await {
- let content_type = field.content_disposition().unwrap();
- let filename = content_type.get_filename().unwrap();
- let filepath = format!("uploaded-images/{}", sanitize_filename::sanitize(&filename));
- let mut f = web::block(|| std::fs::File::create(filepath))
- .await
- .unwrap();
- while let Some(chunk) = field.next().await {
- let data = chunk.unwrap();
- f = web::block(move || f.write_all(&data).map(|_| f)).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"/>
- <button type="submit">Submit</button>
- </form>
- </body>
- </html>"#;
- HttpResponse::Ok()
- .content_type("text/html; charset=utf-8")
- .body(html)
- }
- #[actix_web::main]
- async fn main() -> Result<(), Error> {
- std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
- std::fs::create_dir_all("./uploaded-images").unwrap();
- // Configurable host and port by command line args
- let command_line = clap::App::new("File uploader")
- .arg(Arg::with_name("apphost")
- .short("h")
- .long("host")
- .value_name("APPHOST")
- .help("if empty, default is localhost")
- .takes_value(true))
- .arg(Arg::with_name("appport")
- .short("p")
- .long("port")
- .value_name("APPPORT")
- .help("app port, if empty default is 9000")
- .takes_value(true))
- .get_matches();
- let host = command_line.value_of("host").unwrap_or("127.0.0.1");
- let port = command_line.value_of("port").unwrap_or("9000");
- println!("File uploader server running on {}:{}", host, port);
- HttpServer::new(|| {
- App::new().wrap(middleware::Logger::default())
- .service(
- actix_web::web::resource("/")
- .route(actix_web::web::get().to(index))
- .route(actix_web::web::post().to(save_file)),
- )
- })
- .bind(format!("{}:{}", host, port))?
- .run()
- .await;
- Ok(())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement