Skip to main content

StoredFile

Struct StoredFile 

Source
pub struct StoredFile { /* private fields */ }
Available on crate feature fs only.
Expand description

One received file, in memory or in a temporary file.

Dropping it without persist deletes it (closing the handle first) and wipes memory-held bytes. Debug never prints the file name or the data.

§Examples

use std::io::Read;

let body = b"--X\r\nContent-Disposition: form-data; name=doc; filename=a.txt\r\n\r\nhello\r\n--X--";
let upload = form_net::read_multipart(b"multipart/form-data; boundary=X", &body[..])?;
let file = upload.file("doc").unwrap();
let mut text = String::new();
file.reader()?.read_to_string(&mut text).unwrap();
assert_eq!((text.as_str(), file.len(), file.is_in_memory()), ("hello", 5, true));

Implementations§

Source§

impl StoredFile

Source

pub fn name(&self) -> &str

The form field name.

§Examples
let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a.txt\r\n\r\nhello\r\n--X--";
let upload = form_net::read_multipart(b"multipart/form-data; boundary=X", &body[..])?;
let file = upload.file("f").unwrap();
assert_eq!(file.name(), "f");
Source

pub fn filename(&self) -> Option<FileName<'_>>

The client’s file name: a hint, never a path.

§Examples
let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a.txt\r\n\r\nhello\r\n--X--";
let upload = form_net::read_multipart(b"multipart/form-data; boundary=X", &body[..])?;
let file = upload.file("f").unwrap();
assert_eq!(file.filename().unwrap().as_str()?, "a.txt");
Source

pub fn content_type(&self) -> Option<ContentType<'_>>

The declared content type: a hint, never trusted.

§Examples
let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a.txt\r\nContent-Type: text/plain\r\n\r\nhello\r\n--X--";
let upload = form_net::read_multipart(b"multipart/form-data; boundary=X", &body[..])?;
let file = upload.file("f").unwrap();
assert!(file.content_type().unwrap().is("text", "plain"));
Source

pub const fn len(&self) -> u64

The length in bytes.

§Examples
let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a.txt\r\n\r\nhello\r\n--X--";
let upload = form_net::read_multipart(b"multipart/form-data; boundary=X", &body[..])?;
let file = upload.file("f").unwrap();
assert_eq!(file.len(), 5);
Source

pub const fn is_empty(&self) -> bool

Whether the file is empty.

§Examples
let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a.txt\r\n\r\n\r\n--X--";
let upload = form_net::read_multipart(b"multipart/form-data; boundary=X", &body[..])?;
let file = upload.file("f").unwrap();
assert!(file.is_empty());
Source

pub const fn is_in_memory(&self) -> bool

Whether the file is held in memory.

§Examples
let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a.txt\r\n\r\nhello\r\n--X--";
let upload = form_net::read_multipart(b"multipart/form-data; boundary=X", &body[..])?;
let file = upload.file("f").unwrap();
// Files up to the store's memory threshold never reach the disk.
assert!(file.is_in_memory());
Source

pub fn bytes(&self) -> Option<&[u8]>

The bytes, while the file is in memory.

§Examples
let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a.txt\r\n\r\nhello\r\n--X--";
let upload = form_net::read_multipart(b"multipart/form-data; boundary=X", &body[..])?;
let file = upload.file("f").unwrap();
assert_eq!(file.bytes(), Some(&b"hello"[..]));
Source

pub fn reader(&self) -> Result<StoredReader<'_>, FormError>

A reader over the file, in memory or on disk. It reads with positional reads, so several readers can exist at once.

§Errors

Io { kind } when the file is gone.

§Examples
use std::io::Read;

let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a.txt\r\n\r\nhello\r\n--X--";
let upload = form_net::read_multipart(b"multipart/form-data; boundary=X", &body[..])?;
let file = upload.file("f").unwrap();
let (mut a, mut b) = (file.reader()?, file.reader()?);
let mut first = [0u8; 2];
a.read_exact(&mut first)?;
let mut all = Vec::new();
b.read_to_end(&mut all)?;
assert_eq!((&first, all.as_slice()), (b"he", &b"hello"[..]));
Source

pub fn read_to_vec(&self, max: u64) -> Result<Vec<u8>, FormError>

The whole file in a new vector, refusing a file longer than max before allocating.

§Errors

Limit { FileSize }; Io { kind }.

§Examples
let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a.txt\r\n\r\nhello\r\n--X--";
let upload = form_net::read_multipart(b"multipart/form-data; boundary=X", &body[..])?;
let file = upload.file("f").unwrap();
assert_eq!(file.read_to_vec(1024)?, b"hello");
assert_eq!(file.read_to_vec(4).unwrap_err().code(), "limit.file_size");
Source

pub fn path(&self) -> Option<&Path>

The temporary file’s path, in SpillMode::Named only.

§Examples
use form_net::{Limits, Policy, SpillMode, Store};

let store = Store::in_dir(&dir)?.memory_threshold(0).mode(SpillMode::Named);
let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a.txt\r\n\r\nhello\r\n--X--";
let upload = form_net::read_multipart_with(b"multipart/form-data; boundary=X", &body[..], &Limits::DEFAULT, &Policy::DEFAULT, &store)?;
let path = upload.file("f").unwrap().path().unwrap();
assert!(path.is_file() && path.parent() == Some(dir.as_path()));
Source

pub fn persist(self, dest: &Path) -> Result<(), PersistError>

Moves the finished upload to dest, which the caller built. It never overwrites: a named file is hard-linked when dest is on the same file system and copied otherwise; anonymous and memory files are copied into dest opened with create_new. Whether to fsync dest and its directory is the caller’s choice.

On Unix the persisted file is owner-only (0600) however it was made, as the temporary file was; widen it after persist if others must read it. On Windows it takes the destination directory’s inherited ACL (D-155).

On failure the upload is handed back in the error, untouched, so the caller can try another name; ? into a FormError drops it, which deletes the temporary file (D-154).

§Errors

Store { DestinationExists }; Io { kind }; each with the file.

§Examples
let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a.txt\r\n\r\nhello\r\n--X--";
let mut upload = form_net::read_multipart(b"multipart/form-data; boundary=X", &body[..])?;
let file = upload.take_file("f").unwrap();
std::fs::write(dir.join("a.txt"), b"taken")?;
// The name is taken: the upload comes back, and another name works.
let file = match file.persist(&dir.join("a.txt")) {
    Ok(()) => unreachable!(),
    Err(e) => {
        assert_eq!(e.error().code(), "store.destination_exists");
        e.into_file()
    }
};
file.persist(&dir.join("a (2).txt"))?;
assert_eq!(std::fs::read(dir.join("a (2).txt"))?, b"hello");

Trait Implementations§

Source§

impl Debug for StoredFile

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for StoredFile

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl FromField for StoredFile

Source§

type Slot = (bool, Option<StoredFile>)

Available on crate feature alloc only.

Whether the field arrived (an empty file input counts), and the file.

Source§

fn accept_file( slot: &mut Self::Slot, file: FileValue<'_>, ) -> Result<(), ValueError>

Available on crate feature alloc only.
Takes one file. Read more
Source§

fn finish(slot: Self::Slot) -> Result<Self, ValueError>

Available on crate feature alloc only.
The value, once every field has arrived. Read more
Source§

fn accept_text(slot: &mut Self::Slot, value: &str) -> Result<(), ValueError>

Available on crate feature alloc only.
Takes one text value. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.