静态文件

个别文件

可以使用自定义path模式和NamedFile提供静态文件。为了匹配path尾部,我们可以使用[.*]正则表达式。

use actix_files::NamedFile;
use actix_web::{HttpRequest, Result};
use std::path::PathBuf;

async fn index(req: HttpRequest) -> Result<NamedFile> {
    let path: PathBuf = req.match_info().query("filename").parse().unwrap();
    Ok(NamedFile::open(path)?)
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{web, App, HttpServer};

    HttpServer::new(|| App::new().route("/{filename:.*}", web::get().to(index)))
        .bind("127.0.0.1:8088")?
        .run()
        .await
}

Directory 目录

要提供来自特定目录和子目录的文件,可以使用FilesFiles必须使用App::service()方法注册,否则它将无法提供sub-paths(子路径)

use actix_files as fs;
use actix_web::{App, HttpServer};

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(fs::Files::new("/static", ".").show_files_listing())
    })
    .bind("127.0.0.1:8088")?
    .run()
    .await
}

默认情况下,禁用子目录的文件列表。尝试加载目录列表将返回*404 Not Found*响应。要启用文件列表,请使用Files::show_files_listing()方法。

除了显示目录的文件列表外,还可以重定向到特定的索引文件。使用Files::index_file()方法配置此重定向。

Configuration 配置

NamedFiles可以指定用于提供文件的各种选项:

  • set_content_disposition - 用于将文件的mime映射到相应的Content-Disposition类型的函数
  • use_etag - 指定是否应计算ETag并将其包含在headers中。
  • use_last_modified - 指定是否应使用文件修改的timestamp(时间戳)并将其添加到Last-Modified header中。

上面所有方法都是可选的,并提供了最佳默认值,但是可以自定义它们中的任何一个。

use actix_files as fs;
use actix_web::http::header::{ContentDisposition, DispositionType};
use actix_web::{web, App, Error, HttpRequest, HttpServer};

async fn index(req: HttpRequest) -> Result<fs::NamedFile, Error> {
    let path: std::path::PathBuf = req.match_info().query("filename").parse().unwrap();
    let file = fs::NamedFile::open(path)?;
    Ok(file
        .use_last_modified(true)
        .set_content_disposition(ContentDisposition {
            disposition: DispositionType::Attachment,
            parameters: vec![],
        }))
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().route("/{filename:.*}", web::get().to(index)))
        .bind("127.0.0.1:8088")?
        .run()
        .await
}

该配置也可以应用于目录服务:

use actix_files as fs;
use actix_web::{App, HttpServer};

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(
            fs::Files::new("/static", ".")
                .show_files_listing()
                .use_last_modified(true),
        )
    })
    .bind("127.0.0.1:8088")?
    .run()
    .await
}
接下来: Websockets