aurelin_framework/uploads/
mod.rs1use std::{io, path::Path as FilePath};
11
12use axum::{body::Bytes, extract::DefaultBodyLimit};
13use axum_typed_multipart::FieldData;
14use futures_util::stream;
15use rand::{Rng, distr::Alphanumeric};
16use tempfile::NamedTempFile;
17use tokio::{fs::File, io::AsyncReadExt};
18
19use crate::storage::{Disk, StorageError, StoragePath, StorageResult};
20
21const READ_CHUNK_SIZE: usize = 64 * 1024;
22const GENERATED_NAME_LENGTH: usize = 40;
23
24#[derive(Clone, Debug, Eq, PartialEq)]
26pub struct StoredUpload {
27 pub path: StoragePath,
29 pub size: u64,
31 pub untrusted_original_name: Option<String>,
33 pub untrusted_content_type: Option<String>,
35}
36
37pub fn request_body_limit(max_bytes: usize) -> DefaultBodyLimit {
42 DefaultBodyLimit::max(max_bytes)
43}
44
45pub async fn store_upload(
51 disk: &Disk,
52 directory: Option<&str>,
53 upload: FieldData<NamedTempFile>,
54) -> StorageResult<StoredUpload> {
55 let directory = directory.map(StoragePath::parse).transpose()?;
56 let generated_name: String =
57 rand::rng().sample_iter(Alphanumeric).take(GENERATED_NAME_LENGTH).map(char::from).collect();
58 let path = match directory {
59 Some(directory) => StoragePath::parse(format!("{directory}/{generated_name}"))?,
60 None => StoragePath::parse(generated_name)?,
61 };
62
63 let original_name = upload.metadata.file_name;
64 let content_type = upload.metadata.content_type;
65 let file = open_temporary_file(upload.contents.path()).await?;
66 let stream = file_stream(file);
67 let size = disk.put_stream(path.as_str(), stream).await?;
68
69 Ok(StoredUpload { path, size, untrusted_original_name: original_name, untrusted_content_type: content_type })
70}
71
72async fn open_temporary_file(path: &FilePath) -> StorageResult<File> {
73 File::open(path).await.map_err(StorageError::input)
74}
75
76fn file_stream(file: File) -> impl futures_util::Stream<Item = Result<Bytes, io::Error>> + Send {
77 stream::try_unfold(file, |mut file| async move {
78 let mut buffer = vec![0_u8; READ_CHUNK_SIZE];
79 let read = file.read(&mut buffer).await?;
80 if read == 0 {
81 return Ok(None);
82 }
83 buffer.truncate(read);
84 Ok(Some((Bytes::from(buffer), file)))
85 })
86}
87
88pub use tempfile::NamedTempFile as TemporaryUploadFile;