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
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 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 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>§
pub async fn read_at<T>(&self, buf: T, pos: u64) -> (Result<usize, Error>, T)where
T: IoBufMut,
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:
- The specified offset is the end of the file.
- 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,
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:
- The specified offset is the end of the file.
- 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,
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,
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>
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>
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 ServiceFactory<ServiceRequest> for NamedFile
impl ServiceFactory<ServiceRequest> for NamedFile
§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
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
§impl<SF, Req> IntoServiceFactory<SF, Req> for SFwhere
SF: ServiceFactory<Req>,
impl<SF, Req> IntoServiceFactory<SF, Req> for SFwhere
SF: ServiceFactory<Req>,
§fn into_factory(self) -> SF
fn into_factory(self) -> SF
Self
to a ServiceFactory