Can upload disk images on the server
Some checks failed
continuous-integration/drone/push Build is failing
Some checks failed
continuous-integration/drone/push Build is failing
This commit is contained in:
57
virtweb_backend/src/controllers/disk_images_controller.rs
Normal file
57
virtweb_backend/src/controllers/disk_images_controller.rs
Normal file
@ -0,0 +1,57 @@
|
||||
use crate::app_config::AppConfig;
|
||||
use crate::constants;
|
||||
use crate::controllers::HttpResult;
|
||||
use crate::utils::files_utils;
|
||||
use actix_multipart::form::MultipartForm;
|
||||
use actix_multipart::form::tempfile::TempFile;
|
||||
use actix_web::HttpResponse;
|
||||
|
||||
#[derive(Debug, MultipartForm)]
|
||||
pub struct UploadDiskImageForm {
|
||||
#[multipart(rename = "file")]
|
||||
files: Vec<TempFile>,
|
||||
}
|
||||
|
||||
/// Upload disk image file
|
||||
pub async fn upload(MultipartForm(mut form): MultipartForm<UploadDiskImageForm>) -> HttpResult {
|
||||
if form.files.is_empty() {
|
||||
log::error!("Missing uploaded disk file!");
|
||||
return Ok(HttpResponse::BadRequest().json("Missing file!"));
|
||||
}
|
||||
|
||||
let file = form.files.remove(0);
|
||||
|
||||
// Check uploaded file size
|
||||
if file.size > constants::DISK_IMAGE_MAX_SIZE {
|
||||
return Ok(HttpResponse::BadRequest().json("Disk image max size exceeded!"));
|
||||
}
|
||||
|
||||
// Check file mime type
|
||||
if let Some(mime_type) = file.content_type {
|
||||
if !constants::ALLOWED_DISK_IMAGES_MIME_TYPES.contains(&mime_type.as_ref()) {
|
||||
return Ok(HttpResponse::BadRequest().json(format!(
|
||||
"Unsupported file type for disk upload: {}",
|
||||
mime_type
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
// Extract and check file name
|
||||
let Some(file_name) = file.file_name else {
|
||||
return Ok(HttpResponse::BadRequest().json("Missing file name of uploaded file!"));
|
||||
};
|
||||
if !files_utils::check_file_name(&file_name) {
|
||||
return Ok(HttpResponse::BadRequest().json("Invalid uploaded file name!"));
|
||||
}
|
||||
|
||||
// Check if a file with the same name already exists
|
||||
let dest_path = AppConfig::get().disk_images_storage_path().join(file_name);
|
||||
if dest_path.is_file() {
|
||||
return Ok(HttpResponse::Conflict().json("A file with the same name already exists!"));
|
||||
}
|
||||
|
||||
// Copy the file to the destination
|
||||
file.file.persist(dest_path)?;
|
||||
|
||||
Ok(HttpResponse::Ok().json("Successfully uploaded disk image!"))
|
||||
}
|
Reference in New Issue
Block a user