如何让rust actix web返回直接在浏览器中打开的静态文件

问题描述 投票:0回答:1

我使用 actix-web 提供静态 pdf 文件预览,这是 Rust 代码:

use actix_web::{error::ErrorBadRequest, web, App, HttpRequest, HttpServer, Responder};
use actix_files::{Files, NamedFile};
use mime::Mime;

async fn namefile(req: HttpRequest) -> impl Responder {
    let pdf_file_path = "/Users/xiaoqiangjiang/source/reddwarf/backend/rust-learn/doc/sample.pdf";
    match NamedFile::open(&pdf_file_path) {
        Ok(file) => {
            let content_type: Mime = "application/pdf".parse().unwrap();
            return NamedFile::set_content_type(file, content_type).into_response(&req);
        }
        Err(e) => {
            return ErrorBadRequest("File not Found").into();
        }
    }
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/namefile", web::get().to(namefile))
            .service(Files::new("/static", "./static").show_files_listing())
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

这是

Cargo.toml

[package]
name = "rust-learn"
version = "0.1.0"
edition = "2018"

[dependencies]
actix-web = "4"
actix-files = "0.6.2"
mime = "0.3.17"

[profile.release]
debug = true

但是当我使用 url http://localhost:8080/namefile 在 google chrome 中访问 pdf 时,它会弹出下载窗口。可以在 google chrome 浏览器中预览 pdf 吗?不要弹出下载窗口。

rust
1个回答
0
投票

默认情况下,

Content-Disposition
application/pdf
设置为
attachment
,导致浏览器下载。

需要手动更改为

inline
浏览器才能直接显示:

use actix_files::{Files, NamedFile};
use actix_web::{
    error::ErrorBadRequest,
    http::header::{ContentDisposition, DispositionType},
    web, App, HttpRequest, HttpServer, Responder,
};
use mime::Mime;

async fn namefile(req: HttpRequest) -> impl Responder {
    let pdf_file_path = "dummy.pdf";
    match NamedFile::open(&pdf_file_path) {
        Ok(file) => {
            let content_type: Mime = "application/pdf".parse().unwrap();
            NamedFile::set_content_type(file, content_type)
                .set_content_disposition(ContentDisposition {
                    disposition: DispositionType::Inline,
                    parameters: Vec::new(),
                })
                .into_response(&req)
        }
        Err(e) => {
            return ErrorBadRequest("File not Found").into();
        }
    }
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/namefile", web::get().to(namefile))
            .service(Files::new("/static", "./static").show_files_listing())
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
© www.soinside.com 2019 - 2024. All rights reserved.