4

I'm looking at the actix-multipart example and there's a lot of blocking file IO. Is it possible to send a response before downloading the file? Multipart isn't Send. I want to do something like this:

async fn save_file(mut payload: Multipart) -> Result<HttpResponse, Error> {
    async_std::task::spawn(async {
        // 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);
            // File::create is blocking operation, use threadpool
            let mut f = web::block(|| std::fs::File::create(filepath))
                .await
                .unwrap();
            // 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?;
            }
        }
    });
    Ok(HttpResponse::Ok().into())
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ripread
  • 330
  • 2
  • 10

0 Answers0