upload.rs
1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use actix_web::{Error, HttpResponse, web};
use anyhow::Result;
use async_std::fs::DirBuilder;
use futures::{stream::StreamExt, AsyncWriteExt};
use async_std::fs::OpenOptions;
use crate::{AppData, models::image::{Upload, self}, upload_filename};
use crate::config::CONFIG;
use std::convert::TryFrom;
pub async fn upload( app_data :web::Data<AppData>
, mut body :web::Payload
, request :web::HttpRequest ) -> Result<HttpResponse, Error>
{
let pool = app_data.database_pool.clone();
let worker = app_data.tx_upload_worker.clone();
let upload_uuid = Some(uuid::Uuid::new_v4().as_bytes().to_vec());
let size = request.headers().get("content-length")
. and_then(|h| Some(h.to_str().unwrap().parse::<i32>()))
. unwrap().unwrap();
let mime_type = String::from( request.headers().get("content-type")
. and_then(|h| Some(h.to_str().unwrap()))
. unwrap() );
let upload = Upload {
upload_uuid,
size,
mime_type
};
DirBuilder::new() . recursive(true)
. create(CONFIG.upload_dir())
. await?;
let upload_filename = upload_filename!(upload).unwrap();
let mut output = OpenOptions::new();
let mut output = output
. create(true)
. write(true)
. open(&upload_filename).await?;
while let Some(item) = body.next().await {
output.write_all(&item?).await?;
}
output.flush().await.unwrap();
let pool_for_worker = pool.clone();
Ok( match web::block(move || image::upload(pool, upload)).await {
Ok(image) => {
// TODO handle this as error response...
worker.send((pool_for_worker, image.clone())).await.unwrap();
HttpResponse::Ok().json(image)
},
Err(_) => HttpResponse::InternalServerError().finish()
} )
}