Skip to content

Commit

Permalink
Use async-std in multipart example and treat all errors.
Browse files Browse the repository at this point in the history
  • Loading branch information
Philipp Vollmer committed Jan 11, 2020
1 parent 49308b7 commit ee1bc32
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
1 change: 1 addition & 0 deletions multipart/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ futures = "0.3.1"
actix-multipart = "0.2.0"
actix-web = "2.0.0"
actix-rt = "1.0.0"
async-std = "1.4.0"
23 changes: 12 additions & 11 deletions multipart/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
use std::io::Write;

use actix_multipart::Multipart;
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
use async_std;
use async_std::prelude::*;
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 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)?;
let filepath = format!("./tmp/{}", filename);
// File::create is blocking operation, use threadpool
let mut f = web::block(|| std::fs::File::create(filepath))
.await
.unwrap();
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();
// filesystem operations are blocking, we have to use threadpool
f = web::block(move || f.write_all(&data).map(|_| f)).await?;
f.write_all(&data).await?;
}
}
Ok(HttpResponse::Ok().into())
Expand All @@ -42,7 +43,7 @@ fn index() -> HttpResponse {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
std::fs::create_dir_all("./tmp").unwrap();
async_std::fs::create_dir_all("./tmp").await?;

let ip = "0.0.0.0:3000";

Expand Down

0 comments on commit ee1bc32

Please sign in to comment.