pub struct NamedFile { /* private fields */ }Expand description
A file with an associated name.
NamedFile can be registered as services:
use actix_web::App;
use actix_files::NamedFile;
let file = NamedFile::open_async("./static/index.html").await?;
let app = App::new().service(file);They can also be returned from handlers:
use actix_web::{Responder, get};
use actix_files::NamedFile;
#[get("/")]
async fn index() -> impl Responder {
    NamedFile::open_async("./static/index.html").await
}Implementations§
Source§impl NamedFile
 
impl NamedFile
Sourcepub fn from_file<P: AsRef<Path>>(file: File, path: P) -> Result<NamedFile>
 
pub fn from_file<P: AsRef<Path>>(file: File, path: P) -> Result<NamedFile>
Creates an instance from a previously opened file.
The given path need not exist and is only used to determine the ContentType and
ContentDisposition headers.
§Examples
use std::{
    io::{self, Write as _},
    env,
    fs::File
};
use actix_files::NamedFile;
let mut file = File::create("foo.txt")?;
file.write_all(b"Hello, world!")?;
let named_file = NamedFile::from_file(file, "bar.txt")?;
Ok(())Sourcepub fn open<P: AsRef<Path>>(path: P) -> Result<NamedFile>
 
pub fn open<P: AsRef<Path>>(path: P) -> Result<NamedFile>
Attempts to open a file in read-only mode.
§Examples
use actix_files::NamedFile;
let file = NamedFile::open("foo.txt");Sourcepub async fn open_async<P: AsRef<Path>>(path: P) -> Result<NamedFile>
 
pub async fn open_async<P: AsRef<Path>>(path: P) -> Result<NamedFile>
Attempts to open a file asynchronously in read-only mode.
When the experimental-io-uring crate feature is enabled, this will be async. Otherwise, it
will behave just like open.
§Examples
use actix_files::NamedFile;
let file = NamedFile::open_async("foo.txt").await.unwrap();Sourcepub fn path(&self) -> &Path
 
pub fn path(&self) -> &Path
Returns the filesystem path to this file.
§Examples
use actix_files::NamedFile;
let file = NamedFile::open_async("test.txt").await?;
assert_eq!(file.path().as_os_str(), "foo.txt");Sourcepub fn modified(&self) -> Option<SystemTime>
 
pub fn modified(&self) -> Option<SystemTime>
Returns the time the file was last modified.
Returns None only on unsupported platforms; see std::fs::Metadata::modified().
Therefore, it is usually safe to unwrap this.
Sourcepub fn content_type(&self) -> &Mime
 
pub fn content_type(&self) -> &Mime
Returns the Content-Type header that will be used when serving this file.
Sourcepub fn content_disposition(&self) -> &ContentDisposition
 
pub fn content_disposition(&self) -> &ContentDisposition
Returns the Content-Disposition that will be used when serving this file.
Sourcepub fn content_encoding(&self) -> Option<ContentEncoding>
 
pub fn content_encoding(&self) -> Option<ContentEncoding>
Returns the Content-Encoding that will be used when serving this file.
A return value of None indicates that the content is not already using a compressed
representation and may be subject to compression downstream.
Sourcepub fn set_status_code(self, status: StatusCode) -> Self
 👎Deprecated since 0.7.0: Prefer Responder::customize().
pub fn set_status_code(self, status: StatusCode) -> Self
Responder::customize().Set response status code.
Sourcepub fn set_content_type(self, mime_type: Mime) -> Self
 
pub fn set_content_type(self, mime_type: Mime) -> Self
Sets the Content-Type header that will be used when serving this file. By default the
Content-Type is inferred from the filename extension.
Sourcepub fn set_content_disposition(self, cd: ContentDisposition) -> Self
 
pub fn set_content_disposition(self, cd: ContentDisposition) -> Self
Set the Content-Disposition for serving this file. This allows changing the
inline/attachment disposition as well as the filename sent to the peer.
By default the disposition is inline for text/*, image/*, video/* and
application/{javascript, json, wasm} mime types, and attachment otherwise, and the
filename is taken from the path provided in the open method after converting it to UTF-8
(using to_string_lossy).
Sourcepub fn disable_content_disposition(self) -> Self
 
pub fn disable_content_disposition(self) -> Self
Disables Content-Disposition header.
By default, the Content-Disposition header is sent.
Sourcepub fn set_content_encoding(self, enc: ContentEncoding) -> Self
 
pub fn set_content_encoding(self, enc: ContentEncoding) -> Self
Sets content encoding for this file.
This prevents the Compress middleware from modifying the file contents and signals to
browsers/clients how to decode it. For example, if serving a compressed HTML file (e.g.,
index.html.gz) then use .set_content_encoding(ContentEncoding::Gzip).
Sourcepub fn read_mode_threshold(self, size: u64) -> Self
 
pub fn read_mode_threshold(self, size: u64) -> Self
Sets the size threshold that determines file read mode (sync/async).
When a file is smaller than the threshold (bytes), the reader will switch from synchronous (blocking) file-reads to async reads to avoid blocking the main-thread when processing large files.
Tweaking this value according to your expected usage may lead to signifiant performance
gains (or losses in other handlers, if size is too high).
When the experimental-io-uring crate feature is enabled, file reads are always async.
Default is 0, meaning all files are read asynchronously.
Sourcepub fn use_etag(self, value: bool) -> Self
 
pub fn use_etag(self, value: bool) -> Self
Specifies whether to return ETag header in response.
Default is true.
Sourcepub fn use_last_modified(self, value: bool) -> Self
 
pub fn use_last_modified(self, value: bool) -> Self
Specifies whether to return Last-Modified header in response.
Default is true.
Sourcepub fn prefer_utf8(self, value: bool) -> Self
 
pub fn prefer_utf8(self, value: bool) -> Self
Specifies whether text responses should signal a UTF-8 encoding.
Default is false (but will default to true in a future version).
Sourcepub fn into_response(self, req: &HttpRequest) -> HttpResponse<BoxBody>
 
pub fn into_response(self, req: &HttpRequest) -> HttpResponse<BoxBody>
Creates an HttpResponse with file as a streaming body.
Methods from Deref<Target = File>§
1.0.0 · Sourcepub fn sync_all(&self) -> Result<(), Error>
 
pub fn sync_all(&self) -> Result<(), Error>
Attempts to sync all OS-internal file content and metadata to disk.
This function will attempt to ensure that all in-memory data reaches the filesystem before returning.
This can be used to handle errors that would otherwise only be caught
when the File is closed, as dropping a File will ignore all errors.
Note, however, that sync_all is generally more expensive than closing
a file by dropping it, because the latter is not required to block until
the data has been written to the filesystem.
If synchronizing the metadata is not required, use sync_data instead.
§Examples
use std::fs::File;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
    let mut f = File::create("foo.txt")?;
    f.write_all(b"Hello, world!")?;
    f.sync_all()?;
    Ok(())
}1.0.0 · Sourcepub fn sync_data(&self) -> Result<(), Error>
 
pub fn sync_data(&self) -> Result<(), Error>
This function is similar to sync_all, except that it might not
synchronize file metadata to the filesystem.
This is intended for use cases that must synchronize content, but don’t need the metadata on disk. The goal of this method is to reduce disk operations.
Note that some platforms may simply implement this in terms of
sync_all.
§Examples
use std::fs::File;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
    let mut f = File::create("foo.txt")?;
    f.write_all(b"Hello, world!")?;
    f.sync_data()?;
    Ok(())
}1.89.0 · Sourcepub fn lock(&self) -> Result<(), Error>
 
pub fn lock(&self) -> Result<(), Error>
Acquire an exclusive lock on the file. Blocks until the lock can be acquired.
This acquires an exclusive lock; no other file handle to this file may acquire another lock.
This lock may be advisory or mandatory. This lock is meant to interact with lock,
try_lock, lock_shared, try_lock_shared, and unlock. Its interactions with
other methods, such as read and write are platform specific, and it may or may not
cause non-lockholders to block.
If this file handle/descriptor, or a clone of it, already holds an lock the exact behavior is unspecified and platform dependent, including the possibility that it will deadlock. However, if this method returns, then an exclusive lock is held.
If the file not open for writing, it is unspecified whether this function returns an error.
The lock will be released when this file (along with any other file descriptors/handles
duplicated or inherited from it) is closed, or if the unlock method is called.
§Platform-specific behavior
This function currently corresponds to the flock function on Unix with the LOCK_EX flag,
and the LockFileEx function on Windows with the LOCKFILE_EXCLUSIVE_LOCK flag. Note that,
this may change in the future.
On Windows, locking a file will fail if the file is opened only for append. To lock a file,
open it with one of .read(true), .read(true).append(true), or .write(true).
§Examples
use std::fs::File;
fn main() -> std::io::Result<()> {
    let f = File::create("foo.txt")?;
    f.lock()?;
    Ok(())
}Acquire a shared (non-exclusive) lock on the file. Blocks until the lock can be acquired.
This acquires a shared lock; more than one file handle may hold a shared lock, but none may hold an exclusive lock at the same time.
This lock may be advisory or mandatory. This lock is meant to interact with lock,
try_lock, lock_shared, try_lock_shared, and unlock. Its interactions with
other methods, such as read and write are platform specific, and it may or may not
cause non-lockholders to block.
If this file handle/descriptor, or a clone of it, already holds an lock, the exact behavior is unspecified and platform dependent, including the possibility that it will deadlock. However, if this method returns, then a shared lock is held.
The lock will be released when this file (along with any other file descriptors/handles
duplicated or inherited from it) is closed, or if the unlock method is called.
§Platform-specific behavior
This function currently corresponds to the flock function on Unix with the LOCK_SH flag,
and the LockFileEx function on Windows. Note that, this
may change in the future.
On Windows, locking a file will fail if the file is opened only for append. To lock a file,
open it with one of .read(true), .read(true).append(true), or .write(true).
§Examples
use std::fs::File;
fn main() -> std::io::Result<()> {
    let f = File::open("foo.txt")?;
    f.lock_shared()?;
    Ok(())
}1.89.0 · Sourcepub fn try_lock(&self) -> Result<(), TryLockError>
 
pub fn try_lock(&self) -> Result<(), TryLockError>
Try to acquire an exclusive lock on the file.
Returns Err(TryLockError::WouldBlock) if a different lock is already held on this file
(via another handle/descriptor).
This acquires an exclusive lock; no other file handle to this file may acquire another lock.
This lock may be advisory or mandatory. This lock is meant to interact with lock,
try_lock, lock_shared, try_lock_shared, and unlock. Its interactions with
other methods, such as read and write are platform specific, and it may or may not
cause non-lockholders to block.
If this file handle/descriptor, or a clone of it, already holds an lock, the exact behavior
is unspecified and platform dependent, including the possibility that it will deadlock.
However, if this method returns Ok(true), then it has acquired an exclusive lock.
If the file not open for writing, it is unspecified whether this function returns an error.
The lock will be released when this file (along with any other file descriptors/handles
duplicated or inherited from it) is closed, or if the unlock method is called.
§Platform-specific behavior
This function currently corresponds to the flock function on Unix with the LOCK_EX and
LOCK_NB flags, and the LockFileEx function on Windows with the LOCKFILE_EXCLUSIVE_LOCK
and LOCKFILE_FAIL_IMMEDIATELY flags. Note that, this
may change in the future.
On Windows, locking a file will fail if the file is opened only for append. To lock a file,
open it with one of .read(true), .read(true).append(true), or .write(true).
§Examples
use std::fs::{File, TryLockError};
fn main() -> std::io::Result<()> {
    let f = File::create("foo.txt")?;
    // Explicit handling of the WouldBlock error
    match f.try_lock() {
        Ok(_) => (),
        Err(TryLockError::WouldBlock) => (), // Lock not acquired
        Err(TryLockError::Error(err)) => return Err(err),
    }
    // Alternately, propagate the error as an io::Error
    f.try_lock()?;
    Ok(())
}Try to acquire a shared (non-exclusive) lock on the file.
Returns Err(TryLockError::WouldBlock) if a different lock is already held on this file
(via another handle/descriptor).
This acquires a shared lock; more than one file handle may hold a shared lock, but none may hold an exclusive lock at the same time.
This lock may be advisory or mandatory. This lock is meant to interact with lock,
try_lock, lock_shared, try_lock_shared, and unlock. Its interactions with
other methods, such as read and write are platform specific, and it may or may not
cause non-lockholders to block.
If this file handle, or a clone of it, already holds an lock, the exact behavior is
unspecified and platform dependent, including the possibility that it will deadlock.
However, if this method returns Ok(true), then it has acquired a shared lock.
The lock will be released when this file (along with any other file descriptors/handles
duplicated or inherited from it) is closed, or if the unlock method is called.
§Platform-specific behavior
This function currently corresponds to the flock function on Unix with the LOCK_SH and
LOCK_NB flags, and the LockFileEx function on Windows with the
LOCKFILE_FAIL_IMMEDIATELY flag. Note that, this
may change in the future.
On Windows, locking a file will fail if the file is opened only for append. To lock a file,
open it with one of .read(true), .read(true).append(true), or .write(true).
§Examples
use std::fs::{File, TryLockError};
fn main() -> std::io::Result<()> {
    let f = File::open("foo.txt")?;
    // Explicit handling of the WouldBlock error
    match f.try_lock_shared() {
        Ok(_) => (),
        Err(TryLockError::WouldBlock) => (), // Lock not acquired
        Err(TryLockError::Error(err)) => return Err(err),
    }
    // Alternately, propagate the error as an io::Error
    f.try_lock_shared()?;
    Ok(())
}1.89.0 · Sourcepub fn unlock(&self) -> Result<(), Error>
 
pub fn unlock(&self) -> Result<(), Error>
Release all locks on the file.
All locks are released when the file (along with any other file descriptors/handles duplicated or inherited from it) is closed. This method allows releasing locks without closing the file.
If no lock is currently held via this file descriptor/handle, this method may return an error, or may return successfully without taking any action.
§Platform-specific behavior
This function currently corresponds to the flock function on Unix with the LOCK_UN flag,
and the UnlockFile function on Windows. Note that, this
may change in the future.
On Windows, locking a file will fail if the file is opened only for append. To lock a file,
open it with one of .read(true), .read(true).append(true), or .write(true).
§Examples
use std::fs::File;
fn main() -> std::io::Result<()> {
    let f = File::open("foo.txt")?;
    f.lock()?;
    f.unlock()?;
    Ok(())
}1.0.0 · Sourcepub fn set_len(&self, size: u64) -> Result<(), Error>
 
pub fn set_len(&self, size: u64) -> Result<(), Error>
Truncates or extends the underlying file, updating the size of
this file to become size.
If the size is less than the current file’s size, then the file will
be shrunk. If it is greater than the current file’s size, then the file
will be extended to size and have all of the intermediate data filled
in with 0s.
The file’s cursor isn’t changed. In particular, if the cursor was at the end and the file is shrunk using this operation, the cursor will now be past the end.
§Errors
This function will return an error if the file is not opened for writing.
Also, std::io::ErrorKind::InvalidInput
will be returned if the desired length would cause an overflow due to
the implementation specifics.
§Examples
use std::fs::File;
fn main() -> std::io::Result<()> {
    let mut f = File::create("foo.txt")?;
    f.set_len(10)?;
    Ok(())
}Note that this method alters the content of the underlying file, even
though it takes &self rather than &mut self.
1.0.0 · Sourcepub fn metadata(&self) -> Result<Metadata, Error>
 
pub fn metadata(&self) -> Result<Metadata, Error>
Queries metadata about the underlying file.
§Examples
use std::fs::File;
fn main() -> std::io::Result<()> {
    let mut f = File::open("foo.txt")?;
    let metadata = f.metadata()?;
    Ok(())
}1.9.0 · Sourcepub fn try_clone(&self) -> Result<File, Error>
 
pub fn try_clone(&self) -> Result<File, Error>
Creates a new File instance that shares the same underlying file handle
as the existing File instance. Reads, writes, and seeks will affect
both File instances simultaneously.
§Examples
Creates two handles for a file named foo.txt:
use std::fs::File;
fn main() -> std::io::Result<()> {
    let mut file = File::open("foo.txt")?;
    let file_copy = file.try_clone()?;
    Ok(())
}Assuming there’s a file named foo.txt with contents abcdef\n, create
two handles, seek one of them, and read the remaining bytes from the
other handle:
use std::fs::File;
use std::io::SeekFrom;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
    let mut file = File::open("foo.txt")?;
    let mut file_copy = file.try_clone()?;
    file.seek(SeekFrom::Start(3))?;
    let mut contents = vec![];
    file_copy.read_to_end(&mut contents)?;
    assert_eq!(contents, b"def\n");
    Ok(())
}1.16.0 · Sourcepub fn set_permissions(&self, perm: Permissions) -> Result<(), Error>
 
pub fn set_permissions(&self, perm: Permissions) -> Result<(), Error>
Changes the permissions on the underlying file.
§Platform-specific behavior
This function currently corresponds to the fchmod function on Unix and
the SetFileInformationByHandle function on Windows. Note that, this
may change in the future.
§Errors
This function will return an error if the user lacks permission change attributes on the underlying file. It may also return an error in other os-specific unspecified cases.
§Examples
fn main() -> std::io::Result<()> {
    use std::fs::File;
    let file = File::open("foo.txt")?;
    let mut perms = file.metadata()?.permissions();
    perms.set_readonly(true);
    file.set_permissions(perms)?;
    Ok(())
}Note that this method alters the permissions of the underlying file,
even though it takes &self rather than &mut self.
1.75.0 · Sourcepub fn set_times(&self, times: FileTimes) -> Result<(), Error>
 
pub fn set_times(&self, times: FileTimes) -> Result<(), Error>
Changes the timestamps of the underlying file.
§Platform-specific behavior
This function currently corresponds to the futimens function on Unix (falling back to
futimes on macOS before 10.13) and the SetFileTime function on Windows. Note that this
may change in the future.
§Errors
This function will return an error if the user lacks permission to change timestamps on the underlying file. It may also return an error in other os-specific unspecified cases.
This function may return an error if the operating system lacks support to change one or
more of the timestamps set in the FileTimes structure.
§Examples
fn main() -> std::io::Result<()> {
    use std::fs::{self, File, FileTimes};
    let src = fs::metadata("src")?;
    let dest = File::options().write(true).open("dest")?;
    let times = FileTimes::new()
        .set_accessed(src.accessed()?)
        .set_modified(src.modified()?);
    dest.set_times(times)?;
    Ok(())
}1.75.0 · Sourcepub fn set_modified(&self, time: SystemTime) -> Result<(), Error>
 
pub fn set_modified(&self, time: SystemTime) -> Result<(), Error>
Changes the modification time of the underlying file.
This is an alias for set_times(FileTimes::new().set_modified(time)).
Trait Implementations§
Source§impl HttpServiceFactory for NamedFile
 
impl HttpServiceFactory for NamedFile
fn register(self, config: &mut AppService)
Source§impl Responder for NamedFile
 
impl Responder for NamedFile
type Body = BoxBody
Source§fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body>
 
fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body>
HttpResponse.Source§impl ServiceFactory<ServiceRequest> for NamedFile
 
impl ServiceFactory<ServiceRequest> for NamedFile
Source§type Response = ServiceResponse
 
type Response = ServiceResponse
Source§type Future = Pin<Box<dyn Future<Output = Result<<NamedFile as ServiceFactory<ServiceRequest>>::Service, <NamedFile as ServiceFactory<ServiceRequest>>::InitError>>>>
 
type Future = Pin<Box<dyn Future<Output = Result<<NamedFile as ServiceFactory<ServiceRequest>>::Service, <NamedFile as ServiceFactory<ServiceRequest>>::InitError>>>>
Service instance.gSource§fn new_service(&self, _: ()) -> Self::Future
 
fn new_service(&self, _: ()) -> Self::Future
Auto Trait Implementations§
impl Freeze for NamedFile
impl RefUnwindSafe for NamedFile
impl Send for NamedFile
impl Sync for NamedFile
impl Unpin for NamedFile
impl UnwindSafe for NamedFile
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
    T: ?Sized,
 
impl<T> BorrowMut<T> for Twhere
    T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
 
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
 
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
 
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
 
fn in_current_span(self) -> Instrumented<Self>
Source§impl<SF, Req> IntoServiceFactory<SF, Req> for SFwhere
    SF: ServiceFactory<Req>,
 
impl<SF, Req> IntoServiceFactory<SF, Req> for SFwhere
    SF: ServiceFactory<Req>,
Source§fn into_factory(self) -> SF
 
fn into_factory(self) -> SF
Self to a ServiceFactory