1
0
mirror of https://github.com/actix/examples synced 2025-06-29 02:10:36 +02:00

fix multipart example

This commit is contained in:
Nikolay Kim
2019-12-09 06:28:09 +06:00
parent 9ef1107c0c
commit 998f92d2e3
3 changed files with 18 additions and 34 deletions

View File

@ -1,7 +1,8 @@
use std::io::Write;
use actix_multipart::Multipart;
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
use futures::StreamExt;
use std::io::Write;
async fn save_file(mut payload: Multipart) -> Result<HttpResponse, Error> {
// iterate over multipart stream
@ -10,15 +11,15 @@ async fn save_file(mut payload: Multipart) -> Result<HttpResponse, Error> {
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();
// 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();
let mut pos = 0;
while pos < data.len() {
let bytes_written = f.write(&data[pos..])?;
pos += bytes_written;
}
// filesystem operations are blocking, we have to use threadpool
f = web::block(move || f.write_all(&data).map(|_| f)).await?;
}
}
Ok(HttpResponse::Ok().into())