diff options
| author | Santo Cariotti <santo@dcariotti.me> | 2022-09-10 15:23:02 +0000 |
|---|---|---|
| committer | Santo Cariotti <santo@dcariotti.me> | 2022-09-10 15:23:02 +0000 |
| commit | 2a90d0ff8d4336850a450f749140e2df2e94fc56 (patch) | |
| tree | cf6a0d94ad7f56068093a836d302cdc090747d3a /src | |
| parent | 58d6870c33d664157c3efc9c75686e6c0779a96f (diff) | |
Upload files
Diffstat (limited to 'src')
| -rw-r--r-- | src/config.rs | 2 | ||||
| -rw-r--r-- | src/errors.rs | 7 | ||||
| -rw-r--r-- | src/files.rs | 44 | ||||
| -rw-r--r-- | src/main.rs | 1 |
4 files changed, 54 insertions, 0 deletions
diff --git a/src/config.rs b/src/config.rs index 6449a3f..5783656 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1 +1,3 @@ pub static PAGE_LIMIT: i64 = 20; +pub const MAX_UPLOAD_FILE_SIZE: u64 = 1024 * 1024; // 1 MB +pub const SAVE_FILE_BASE_PATH: &str = "./uploads"; diff --git a/src/errors.rs b/src/errors.rs index 72eb837..2251ad4 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -55,3 +55,10 @@ impl From<sqlx::Error> for AppError { AppError::Database } } + +/// Raise a generic error from a string +impl From<std::string::String> for AppError { + fn from(error: std::string::String) -> AppError { + AppError::BadRequest(error) + } +} diff --git a/src/files.rs b/src/files.rs new file mode 100644 index 0000000..63b8eec --- /dev/null +++ b/src/files.rs @@ -0,0 +1,44 @@ +use crate::config::SAVE_FILE_BASE_PATH; +use crate::errors::AppError; +use axum::extract::Multipart; + +use rand::random; + +/// Upload a file. Returns an `AppError` or the path of the uploaded file +pub async fn upload( + mut multipart: Multipart, + allowed_extensions: Vec<&str>, +) -> Result<String, AppError> { + let mut save_filename = String::new(); + + if let Some(file) = multipart.next_field().await.unwrap() { + let content_type = file.content_type().unwrap().to_string(); + + let index = content_type + .find("/") + .map(|i| i) + .unwrap_or(usize::max_value()); + let mut ext_name = "xxx"; + if index != usize::max_value() { + ext_name = &content_type[index + 1..]; + } + + if allowed_extensions + .iter() + .position(|&x| x.to_lowercase() == ext_name) + .is_some() + { + let rnd = (random::<f32>() * 1000000000 as f32) as i32; + + save_filename = format!("{}/{}.{}", SAVE_FILE_BASE_PATH, rnd, ext_name); + + let data = file.bytes().await.unwrap(); + + tokio::fs::write(&save_filename, &data) + .await + .map_err(|err| err.to_string())?; + } + } + + Ok(save_filename) +} diff --git a/src/main.rs b/src/main.rs index 4f548d2..f0d7661 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ mod config; mod db; mod errors; +mod files; mod logger; mod models; mod pagination; |
