Struct actix_files::NamedFile

source ·
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

source

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(())
source

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");
source

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();
source

pub fn file(&self) -> &File

Returns reference to the underlying file object.

source

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");
source

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.

source

pub fn metadata(&self) -> &Metadata

Returns the filesystem metadata associated with this file.

source

pub fn content_type(&self) -> &Mime

Returns the Content-Type header that will be used when serving this file.

source

pub fn content_disposition(&self) -> &ContentDisposition

Returns the Content-Disposition that will be used when serving this file.

source

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.

source

pub fn set_status_code(self, status: StatusCode) -> Self

👎Deprecated since 0.7.0: Prefer Responder::customize().

Set response status code.

source

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.

source

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).

source

pub fn disable_content_disposition(self) -> Self

Disables Content-Disposition header.

By default, the Content-Disposition header is sent.

source

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).

source

pub fn use_etag(self, value: bool) -> Self

Specifies whether to return ETag header in response.

Default is true.

source

pub fn use_last_modified(self, value: bool) -> Self

Specifies whether to return Last-Modified header in response.

Default is true.

source

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).

source

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 · source

pub fn sync_all(&self) -> Result<(), Error>

Attempts to sync all OS-internal 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. Dropping a file will ignore errors in synchronizing this in-memory data.

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 · source

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.0.0 · source

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 · source

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 · source

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 · source

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 · source

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 · source

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 Debug for NamedFile

source§

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

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

impl Deref for NamedFile

§

type Target = File

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl DerefMut for NamedFile

source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
source§

impl HttpServiceFactory for NamedFile

source§

fn register(self, config: &mut AppService)

source§

impl Responder for NamedFile

§

type Body = BoxBody

source§

fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body>

Convert self to HttpResponse.
source§

fn customize(self) -> CustomizeResponder<Self>
where Self: Sized,

Wraps responder to allow alteration of its response. Read more
source§

impl ServiceFactory<ServiceRequest> for NamedFile

§

type Response = ServiceResponse

Responses given by the created services.
§

type Error = Error

Errors produced by the created services.
§

type Config = ()

Service factory configuration.
§

type Service = NamedFileService

The kind of Service created by this factory.
§

type InitError = ()

Errors potentially raised while building a service.
§

type Future = Pin<Box<dyn Future<Output = Result<<NamedFile as ServiceFactory<ServiceRequest>>::Service, <NamedFile as ServiceFactory<ServiceRequest>>::InitError>>>>

The future of the Service instance.g
source§

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

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> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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<SF, Req> IntoServiceFactory<SF, Req> for SF
where SF: ServiceFactory<Req>,

source§

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<SF, Req> ServiceFactoryExt<Req> for SF
where SF: ServiceFactory<Req>,

source§

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where Self: Sized, F: FnMut(Self::Response) -> R + Clone,

Map this service’s output to a different type, returning a new service of the resulting type.
source§

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where Self: Sized, F: Fn(Self::Error) -> E + Clone,

Map this service’s error to a different error, returning a new service.
source§

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where Self: Sized, F: Fn(Self::InitError) -> E + Clone,

Map this factory’s init error to a different error, returning a new service.
source§

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where Self: Sized, Self::Config: Clone, I: IntoServiceFactory<SF1, Self::Response>, SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
source§

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

§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

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

§

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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more