Skip to main content

serenade_form/
file.rs

1//! Uploaded file payload for [`crate::FieldKind::File`].
2
3use std::path::Path;
4
5use tempfile::NamedTempFile;
6
7use crate::FormError;
8
9/// How an uploaded file is retained after multipart parse.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum FileStorage {
12    /// Keep the entire payload in memory ([`UploadedFile::as_bytes`]).
13    #[default]
14    Memory,
15    /// Spill the payload to a named temporary file ([`UploadedFile::path`]).
16    TempFile,
17}
18
19/// One uploaded file from a `multipart/form-data` part.
20#[derive(Debug)]
21pub struct UploadedFile {
22    filename: Option<String>,
23    content_type: Option<String>,
24    payload: FilePayload,
25}
26
27#[derive(Debug)]
28enum FilePayload {
29    Bytes(Vec<u8>),
30    Temp(NamedTempFile),
31}
32
33impl UploadedFile {
34    /// Builds an in-memory upload (tests and Memory storage).
35    #[must_use]
36    pub const fn from_bytes(
37        filename: Option<String>,
38        content_type: Option<String>,
39        bytes: Vec<u8>,
40    ) -> Self {
41        Self {
42            filename,
43            content_type,
44            payload: FilePayload::Bytes(bytes),
45        }
46    }
47
48    /// Builds a tempfile-backed upload.
49    ///
50    /// # Errors
51    ///
52    /// Returns [`FormError::Upload`] when the tempfile cannot be created or written.
53    pub fn from_tempfile(
54        filename: Option<String>,
55        content_type: Option<String>,
56        bytes: &[u8],
57    ) -> Result<Self, FormError> {
58        let mut file = NamedTempFile::new()
59            .map_err(|err| FormError::Upload(format!("failed to create tempfile: {err}")))?;
60        std::io::Write::write_all(&mut file, bytes)
61            .map_err(|err| FormError::Upload(format!("failed to write tempfile: {err}")))?;
62        Ok(Self {
63            filename,
64            content_type,
65            payload: FilePayload::Temp(file),
66        })
67    }
68
69    /// Client-supplied filename when present.
70    #[must_use]
71    pub fn filename(&self) -> Option<&str> {
72        self.filename.as_deref()
73    }
74
75    /// Client-supplied `Content-Type` when present.
76    #[must_use]
77    pub fn content_type(&self) -> Option<&str> {
78        self.content_type.as_deref()
79    }
80
81    /// Byte length of the payload.
82    #[must_use]
83    pub fn len(&self) -> usize {
84        match &self.payload {
85            FilePayload::Bytes(bytes) => bytes.len(),
86            FilePayload::Temp(file) => file
87                .as_file()
88                .metadata()
89                .map_or(0, |meta| usize::try_from(meta.len()).unwrap_or(usize::MAX)),
90        }
91    }
92
93    /// Returns `true` when the payload is empty.
94    #[must_use]
95    pub fn is_empty(&self) -> bool {
96        self.len() == 0
97    }
98
99    /// In-memory bytes when storage is [`FileStorage::Memory`].
100    #[must_use]
101    pub const fn as_bytes(&self) -> Option<&[u8]> {
102        match &self.payload {
103            FilePayload::Bytes(bytes) => Some(bytes.as_slice()),
104            FilePayload::Temp(_) => None,
105        }
106    }
107
108    /// Filesystem path when storage is [`FileStorage::TempFile`].
109    #[must_use]
110    pub fn path(&self) -> Option<&Path> {
111        match &self.payload {
112            FilePayload::Bytes(_) => None,
113            FilePayload::Temp(file) => Some(file.path()),
114        }
115    }
116
117    /// Consumes the upload and returns the raw bytes.
118    ///
119    /// # Errors
120    ///
121    /// Returns [`FormError::Upload`] when a tempfile cannot be read.
122    pub fn into_bytes(self) -> Result<Vec<u8>, FormError> {
123        match self.payload {
124            FilePayload::Bytes(bytes) => Ok(bytes),
125            FilePayload::Temp(file) => std::fs::read(file.path())
126                .map_err(|err| FormError::Upload(format!("failed to read tempfile: {err}"))),
127        }
128    }
129}