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

pub async fn read_at<T>(&self, buf: T, pos: u64) -> (Result<usize, Error>, T)
where T: IoBufMut,

Read some bytes at the specified offset from the file into the specified buffer, returning how many bytes were read.

§Return

The method returns the operation result and the same buffer value passed as an argument.

If the method returns [Ok(n)], then the read was successful. A nonzero n value indicates that the buffer has been filled with n bytes of data from the file. If n is 0, then one of the following happened:

  1. The specified offset is the end of the file.
  2. The buffer specified was 0 bytes in length.

It is not an error if the returned value n is smaller than the buffer size, even when the file contains enough data to fill the buffer.

§Errors

If this function encounters any form of I/O or other error, an error variant will be returned. The buffer is returned on error.

§Examples
use tokio_uring::fs::File;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    tokio_uring::start(async {
        let f = File::open("foo.txt").await?;
        let buffer = vec![0; 10];

        // Read up to 10 bytes
        let (res, buffer) = f.read_at(buffer, 0).await;
        let n = res?;

        println!("The bytes: {:?}", &buffer[..n]);

        // Close the file
        f.close().await?;
        Ok(())
    })
}

pub async fn readv_at<T>( &self, bufs: Vec<T>, pos: u64 ) -> (Result<usize, Error>, Vec<T>)
where T: IoBufMut,

Read some bytes at the specified offset from the file into the specified array of buffers, returning how many bytes were read.

§Return

The method returns the operation result and the same array of buffers passed as an argument.

If the method returns [Ok(n)], then the read was successful. A nonzero n value indicates that the buffers have been filled with n bytes of data from the file. If n is 0, then one of the following happened:

  1. The specified offset is the end of the file.
  2. The buffers specified were 0 bytes in length.

It is not an error if the returned value n is smaller than the buffer size, even when the file contains enough data to fill the buffer.

§Errors

If this function encounters any form of I/O or other error, an error variant will be returned. The buffer is returned on error.

§Examples
use tokio_uring::fs::File;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    tokio_uring::start(async {
        let f = File::open("foo.txt").await?;
        let buffers = vec![Vec::<u8>::with_capacity(10), Vec::<u8>::with_capacity(10)];

        // Read up to 20 bytes
        let (res, buffer) = f.readv_at(buffers, 0).await;
        let n = res?;

        println!("Read {} bytes", n);

        // Close the file
        f.close().await?;
        Ok(())
    })
}

pub async fn writev_at<T>( &self, buf: Vec<T>, pos: u64 ) -> (Result<usize, Error>, Vec<T>)
where T: IoBuf,

Write data from buffers into this file at the specified offset, returning how many bytes were written.

This function will attempt to write the entire contents of bufs, but the entire write may not succeed, or the write may also generate an error. The bytes will be written starting at the specified offset.

§Return

The method returns the operation result and the same array of buffers passed in as an argument. A return value of 0 typically means that the underlying file is no longer able to accept bytes and will likely not be able to in the future as well, or that the buffer provided is empty.

§Errors

Each call to write may generate an I/O error indicating that the operation could not be completed. If an error is returned then no bytes in the buffer were written to this writer.

It is not considered an error if the entire buffer could not be written to this writer.

§Examples
use tokio_uring::fs::File;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    tokio_uring::start(async {
        let file = File::create("foo.txt").await?;

        // Writes some prefix of the byte string, not necessarily all of it.
        let bufs = vec!["some".to_owned().into_bytes(), " bytes".to_owned().into_bytes()];
        let (res, _) = file.writev_at(bufs, 0).await;
        let n = res?;

        println!("wrote {} bytes", n);

        // Close the file
        file.close().await?;
        Ok(())
    })
}

pub async fn write_at<T>(&self, buf: T, pos: u64) -> (Result<usize, Error>, T)
where T: IoBuf,

Write a buffer into this file at the specified offset, returning how many bytes were written.

This function will attempt to write the entire contents of buf, but the entire write may not succeed, or the write may also generate an error. The bytes will be written starting at the specified offset.

§Return

The method returns the operation result and the same buffer value passed in as an argument. A return value of 0 typically means that the underlying file is no longer able to accept bytes and will likely not be able to in the future as well, or that the buffer provided is empty.

§Errors

Each call to write may generate an I/O error indicating that the operation could not be completed. If an error is returned then no bytes in the buffer were written to this writer.

It is not considered an error if the entire buffer could not be written to this writer.

§Examples
use tokio_uring::fs::File;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    tokio_uring::start(async {
        let file = File::create("foo.txt").await?;

        // Writes some prefix of the byte string, not necessarily all of it.
        let (res, _) = file.write_at(&b"some bytes"[..], 0).await;
        let n = res?;

        println!("wrote {} bytes", n);

        // Close the file
        file.close().await?;
        Ok(())
    })
}

pub async 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 completing.

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 tokio_uring::fs::File;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    tokio_uring::start(async {
        let f = File::create("foo.txt").await?;
        let (res, buf) = f.write_at(&b"Hello, world!"[..], 0).await;
        let n = res?;

        f.sync_all().await?;

        // Close the file
        f.close().await?;
        Ok(())
    })
}

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

Attempts to sync file data to disk.

This method is similar to sync_all, except that it may 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 tokio_uring::fs::File;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    tokio_uring::start(async {
        let f = File::create("foo.txt").await?;
        let (res, buf) = f.write_at(&b"Hello, world!"[..], 0).await;
        let n = res?;

        f.sync_data().await?;

        // Close the file
        f.close().await?;
        Ok(())
    })
}

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

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.

§

impl<T> Instrument for T

§

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

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

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.

§

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

§

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
source§

impl<T> Same for T

§

type Output = T

Should always be Self
§

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

§

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

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

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

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

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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