Loco Starter Example async fs
This commit is contained in:
parent
562778f61d
commit
f3ff417ec4
@ -1,11 +1,12 @@
|
|||||||
#![allow(clippy::missing_errors_doc)]
|
#![allow(clippy::missing_errors_doc)]
|
||||||
#![allow(clippy::unnecessary_struct_initialization)]
|
#![allow(clippy::unnecessary_struct_initialization)]
|
||||||
#![allow(clippy::unused_async)]
|
#![allow(clippy::unused_async)]
|
||||||
use std::{fs, io::Write, path::PathBuf};
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use axum::{body::Body, debug_handler, extract::Multipart};
|
use axum::{body::Body, debug_handler, extract::Multipart};
|
||||||
use loco_rs::prelude::*;
|
use loco_rs::prelude::*;
|
||||||
use sea_orm::QueryOrder;
|
use sea_orm::QueryOrder;
|
||||||
|
use tokio::{fs, io::AsyncWriteExt};
|
||||||
use tokio_util::io::ReaderStream;
|
use tokio_util::io::ReaderStream;
|
||||||
|
|
||||||
use crate::models::_entities::files;
|
use crate::models::_entities::files;
|
||||||
@ -46,16 +47,17 @@ pub async fn upload(
|
|||||||
let uuid = uuid::Uuid::new_v4().to_string();
|
let uuid = uuid::Uuid::new_v4().to_string();
|
||||||
let folder = format!("{now}_{uuid}");
|
let folder = format!("{now}_{uuid}");
|
||||||
let upload_folder = PathBuf::from(UPLOAD_DIR).join(&folder);
|
let upload_folder = PathBuf::from(UPLOAD_DIR).join(&folder);
|
||||||
fs::create_dir_all(&upload_folder)?;
|
fs::create_dir_all(&upload_folder).await?;
|
||||||
|
|
||||||
// Write the file into the newly created folder
|
// Write the file into the newly created folder
|
||||||
let path = upload_folder.join(file_name);
|
let path = upload_folder.join(file_name);
|
||||||
let mut f = fs::OpenOptions::new()
|
let mut f = fs::OpenOptions::new()
|
||||||
.create_new(true)
|
.create_new(true)
|
||||||
.write(true)
|
.write(true)
|
||||||
.open(&path)?;
|
.open(&path)
|
||||||
f.write_all(&content)?;
|
.await?;
|
||||||
f.flush()?;
|
f.write_all(&content).await?;
|
||||||
|
f.flush().await?;
|
||||||
|
|
||||||
// Record the file upload in database
|
// Record the file upload in database
|
||||||
let file = files::ActiveModel {
|
let file = files::ActiveModel {
|
||||||
@ -107,7 +109,7 @@ pub async fn view(
|
|||||||
.expect("File not found");
|
.expect("File not found");
|
||||||
|
|
||||||
// Stream the file
|
// Stream the file
|
||||||
let file = tokio::fs::File::open(format!("{UPLOAD_DIR}/{}", file.file_path)).await?;
|
let file = fs::File::open(format!("{UPLOAD_DIR}/{}", file.file_path)).await?;
|
||||||
let stream = ReaderStream::new(file);
|
let stream = ReaderStream::new(file);
|
||||||
let body = Body::from_stream(stream);
|
let body = Body::from_stream(stream);
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user