1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2025-02-01 20:02:20 +00:00
actix-web/guide/src/qs_12.md

55 lines
1.5 KiB
Markdown
Raw Normal View History

2017-12-02 08:24:26 +00:00
# Static file handling
2017-12-04 02:15:09 +00:00
## Individual file
It is possible to serve static files with a custom path pattern and `NamedFile`. To
match a path tail, we can use a `[.*]` regex.
2017-12-04 02:15:09 +00:00
```rust
2017-12-05 00:26:40 +00:00
# extern crate actix_web;
2017-12-04 02:15:09 +00:00
use std::path::PathBuf;
2018-03-31 07:16:55 +00:00
use actix_web::{App, HttpRequest, Result, http::Method, fs::NamedFile};
2017-12-04 02:15:09 +00:00
2018-03-31 00:31:18 +00:00
fn index(req: HttpRequest) -> Result<NamedFile> {
2017-12-04 02:15:09 +00:00
let path: PathBuf = req.match_info().query("tail")?;
2018-03-31 00:31:18 +00:00
Ok(NamedFile::open(path)?)
2017-12-04 02:15:09 +00:00
}
fn main() {
2018-03-31 07:16:55 +00:00
App::new()
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
2017-12-04 02:15:09 +00:00
.finish();
}
```
## Directory
To serve files from specific directories and sub-directories, `StaticFiles` can be used.
`StaticFiles` must be registered with an `App::handler()` method, otherwise
it will be unable to serve sub-paths.
2017-12-04 02:15:09 +00:00
```rust
2017-12-05 00:26:40 +00:00
# extern crate actix_web;
use actix_web::*;
2017-12-04 02:15:09 +00:00
fn main() {
2018-03-31 07:16:55 +00:00
App::new()
2018-04-07 02:34:55 +00:00
.handler(
"/static",
fs::StaticFiles::new(".")
2018-04-07 03:24:49 +00:00
.show_files_listing())
2017-12-04 02:15:09 +00:00
.finish();
}
```
2018-04-07 02:34:55 +00:00
The parameter is the base directory. By default files listing for sub-directories
is disabled. Attempt to load directory listing will return *404 Not Found* response.
To enable files listing, use
[*StaticFiles::show_files_listing()*](../actix_web/s/struct.StaticFiles.html#method.show_files_listing)
method.
2018-01-29 11:23:45 +00:00
2018-04-07 02:34:55 +00:00
Instead of showing files listing for directory, it is possible to redirect
to a specific index file. Use the
2018-01-29 11:23:45 +00:00
[*StaticFiles::index_file()*](../actix_web/s/struct.StaticFiles.html#method.index_file)
method to configure this redirect.