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
sourceimpl 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 file(&self) -> &FileⓘNotable traits for Fileimpl Write for Fileimpl Write for &Fileimpl Read for &Fileimpl Read for File
pub fn file(&self) -> &FileⓘNotable traits for Fileimpl Write for Fileimpl Write for &Fileimpl Read for &Fileimpl Read for File
Returns reference to the underlying file object.
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
Prefer 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 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 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 · 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.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
.
Trait Implementations
sourceimpl HttpServiceFactory for NamedFile
impl HttpServiceFactory for NamedFile
fn register(self, config: &mut AppService)
sourceimpl Responder for NamedFile
impl Responder for NamedFile
type Body = BoxBody
sourcefn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body>
fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body>
Convert self to HttpResponse
.
sourcefn customize(self) -> CustomizeResponder<Self>
fn customize(self) -> CustomizeResponder<Self>
Wraps responder to allow alteration of its response. Read more
sourceimpl ServiceFactory<ServiceRequest> for NamedFile
impl ServiceFactory<ServiceRequest> for NamedFile
type Response = ServiceResponse<BoxBody>
type Response = ServiceResponse<BoxBody>
Responses given by the created services.
type Service = NamedFileService
type Service = NamedFileService
The kind of Service
created by this factory.
type Future = Pin<Box<dyn Future<Output = Result<<NamedFile as ServiceFactory<ServiceRequest>>::Service, <NamedFile as ServiceFactory<ServiceRequest>>::InitError>> + 'static, Global>>
type Future = Pin<Box<dyn Future<Output = Result<<NamedFile as ServiceFactory<ServiceRequest>>::Service, <NamedFile as ServiceFactory<ServiceRequest>>::InitError>> + 'static, Global>>
The future of the Service
instance.g
sourcefn new_service(&self, _: ()) -> Self::Future
fn new_service(&self, _: ()) -> Self::Future
Create and return a new service asynchronously.
Auto Trait Implementations
impl RefUnwindSafe for NamedFile
impl Send for NamedFile
impl Sync for NamedFile
impl Unpin for NamedFile
impl UnwindSafe for NamedFile
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
sourceimpl<SF, Req> IntoServiceFactory<SF, Req> for SF where
SF: ServiceFactory<Req>,
impl<SF, Req> IntoServiceFactory<SF, Req> for SF where
SF: ServiceFactory<Req>,
sourcefn into_factory(self) -> SF
fn into_factory(self) -> SF
Convert Self
to a ServiceFactory
sourceimpl<SF, Req> ServiceFactoryExt<Req> for SF where
SF: ServiceFactory<Req>,
impl<SF, Req> ServiceFactoryExt<Req> for SF where
SF: ServiceFactory<Req>,
sourcefn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R> where
F: FnMut(Self::Response) -> R + Clone,
fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R> where
F: FnMut(Self::Response) -> R + Clone,
Map this service’s output to a different type, returning a new service of the resulting type. Read more
sourcefn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E> where
F: Fn(Self::Error) -> E + Clone,
fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E> where
F: Fn(Self::Error) -> E + Clone,
Map this service’s error to a different error, returning a new service.
sourcefn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E> where
F: Fn(Self::InitError) -> E + Clone,
fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E> where
F: Fn(Self::InitError) -> E + Clone,
Map this factory’s init error to a different error, returning a new service.
sourcefn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req> where
I: IntoServiceFactory<SF1, Self::Response>,
SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,
Self::Config: Clone,
fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req> where
I: IntoServiceFactory<SF1, Self::Response>,
SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,
Self::Config: Clone,
Call another service after call to this one has resolved successfully.
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
fn vzip(self) -> V
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
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
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more