Skip to content

Commit f3ff417

Browse files
committed
Loco Starter Example async fs
1 parent 562778f commit f3ff417

File tree

1 file changed

+8
-6
lines changed
  • examples/loco_starter/src/controllers

1 file changed

+8
-6
lines changed

examples/loco_starter/src/controllers/files.rs

+8-6
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
#![allow(clippy::missing_errors_doc)]
22
#![allow(clippy::unnecessary_struct_initialization)]
33
#![allow(clippy::unused_async)]
4-
use std::{fs, io::Write, path::PathBuf};
4+
use std::path::PathBuf;
55

66
use axum::{body::Body, debug_handler, extract::Multipart};
77
use loco_rs::prelude::*;
88
use sea_orm::QueryOrder;
9+
use tokio::{fs, io::AsyncWriteExt};
910
use tokio_util::io::ReaderStream;
1011

1112
use crate::models::_entities::files;
@@ -46,16 +47,17 @@ pub async fn upload(
4647
let uuid = uuid::Uuid::new_v4().to_string();
4748
let folder = format!("{now}_{uuid}");
4849
let upload_folder = PathBuf::from(UPLOAD_DIR).join(&folder);
49-
fs::create_dir_all(&upload_folder)?;
50+
fs::create_dir_all(&upload_folder).await?;
5051

5152
// Write the file into the newly created folder
5253
let path = upload_folder.join(file_name);
5354
let mut f = fs::OpenOptions::new()
5455
.create_new(true)
5556
.write(true)
56-
.open(&path)?;
57-
f.write_all(&content)?;
58-
f.flush()?;
57+
.open(&path)
58+
.await?;
59+
f.write_all(&content).await?;
60+
f.flush().await?;
5961

6062
// Record the file upload in database
6163
let file = files::ActiveModel {
@@ -107,7 +109,7 @@ pub async fn view(
107109
.expect("File not found");
108110

109111
// Stream the file
110-
let file = tokio::fs::File::open(format!("{UPLOAD_DIR}/{}", file.file_path)).await?;
112+
let file = fs::File::open(format!("{UPLOAD_DIR}/{}", file.file_path)).await?;
111113
let stream = ReaderStream::new(file);
112114
let body = Body::from_stream(stream);
113115

0 commit comments

Comments
 (0)