You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
OneAuth/oab/src/api/upload.rs

69 lines
1.7 KiB
Rust

2 years ago
//
// upload.rs
// Copyright (C) 2023 veypi <i@veypi.com>
// 2023-10-03 21:50
// Distributed under terms of the MIT license.
//
//
use std::{fs, path::Path};
2 years ago
use actix_multipart::form::{tempfile::TempFile, MultipartForm};
2 years ago
use actix_web::{post, web, Responder};
use proc::access_read;
use tracing::{info, warn};
use crate::{models::Token, AppState, Error, Result};
2 years ago
#[derive(Debug, MultipartForm)]
struct UploadForm {
files: Vec<TempFile>,
}
#[post("/upload/{dir:.*}")]
2 years ago
#[access_read("app")]
async fn save_files(
MultipartForm(form): MultipartForm<UploadForm>,
t: web::ReqData<Token>,
dir: web::Path<String>,
2 years ago
stat: web::Data<AppState>,
) -> Result<impl Responder> {
let t = t.into_inner();
let mut dir = dir.into_inner();
if dir.is_empty() {
dir = "tmp".to_string();
}
2 years ago
let mut res: Vec<String> = Vec::new();
2 years ago
for v in form.files.into_iter() {
let fname = v.file_name.clone().unwrap_or("unknown".to_string());
let root = Path::new(&stat.media_path).join(dir.clone());
if !root.exists() {
match fs::create_dir_all(root.clone()) {
Ok(_) => {}
Err(e) => {
warn!("{}", e);
}
}
}
let temp_file = format!(
"{}/{}.{}",
root.to_str().unwrap_or(&stat.media_path),
t.id,
fname
);
2 years ago
info!("saving {:?} to {temp_file}", v.file.path().to_str());
match fs::copy(v.file.path(), &temp_file) {
Ok(p) => {
info!("{:#?}", p);
res.push(format!("/media/{}/{}.{}", dir, t.id, fname))
2 years ago
}
Err(e) => {
warn!("{}", e);
}
};
2 years ago
}
2 years ago
Ok(web::Json(res))
}