在先前的文章中,我们介绍了能让 Rocket 框架直接回应 MongoDB 文件中心里的文件的方法。如果想要让网页浏览器在收到服务器传来的文件数据时,将其下载成文件的话,可以参考这篇文章。

File Center Download Response on MongoDB for Rocket Framework

「File Center Download Response on MongoDB for Rocket Framework」是笔者开发的套件,可以让「Mongo File Center」套件融入 Rocket 框架中,能直接从文件中心回应文件数据,并且让网页浏览器直接将其下载成文件。

Crates.io

Cargo.toml

rocket-mongo-file-center-download-response = "*"

使用方法

先将 mongo_file_center 这个 crate 下的 FileCenter 结构实体注册至 Rocket 框架的应用程序状态中。在路由处理程序中,可以利用 State<FileCenter> 的 inner 方法取得 FileCenter 结构实体的参考。

rocket_mongo_file_center_download_response 这个 crate 提供了 FileCenterDownloadResponse 结构体。

FileCenterDownloadResponse 结构体有三个关联函数可以用来产生 FileCenterDownloadResponse 结构体的实体。

首先介绍最常用的 from_id_token 函数。调用 from_id_token 函数时,要从参数传入 FileCenter 结构实体的参考、文件中心加密过的 Object ID(ID token)。下载时的文件名称预设会使用文件中心保存的文件名称,如果要另外设置,可以调用 FileCenterDownloadResponse 结构实体的 file_name 方法。

以下是一个完整的例子:

#[macro_use]
extern crate rocket;

use std::error::Error;
use std::path::Path;

use rocket_mongo_file_center_download_response::mongo_file_center::{mime, FileCenter};
use rocket_mongo_file_center_download_response::FileCenterDownloadResponse;

use rocket::http::Status;
use rocket::State;

const URL: &str = "mongodb://localhost:27017";

#[get("/<id_token>")]
async fn download(
    file_center: &State<FileCenter>,
    id_token: String,
) -> Result<Option<FileCenterDownloadResponse>, Status> {
    FileCenterDownloadResponse::from_id_token(file_center.inner(), id_token)
        .await
        .map_err(|_| Status::InternalServerError)
}


#[rocket::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let file_center = FileCenter::new(URL).await?;

    let path = Path::new("examples").join("images").join("image(猫).jpg");

    let file_id =
        file_center.put_file_by_path(path, None::<String>, Some(mime::IMAGE_JPEG)).await?;

    let id_token = file_center.encrypt_id(file_id);

    println!("The ID token is: {}", id_token);

    println!();

    rocket::build().manage(file_center).mount("/", routes![download]).launch().await?;

    Ok(())
}

程序一开始,会将工作目录下的 examples/images/image(猫).jpg 这张 JPEG 图档保存到文件中心中,然后在屏幕上显示出这笔加密过的 Object ID(也就是「ID token」)。接着将文件中心注册给 Rocket,并启动 Rocket。在 download 这个路由处理程序中,会读取网址路径中带的 ID token。from_id_token 会根据这个 ID token 来查找文件中心里对应的文件,并回传 Result<Option<FileCenterDownloadResponse>, FileCenterError>,注意因为这边的 FileCenterError 并没有实作 rocket::response::Responder 特性,所以不能直接拿来回传,要像范例程序这样先用 map_err 方法转成 Status 等有实作 Responder 特性的类型。

如果是要用 from_object_id 关联函数来创建 FileCenterDownloadResponse 结构实体,把以上的 download 路由处理程序用 from_object_id 关联函数改写的话就会变成以下这样:

#[get("/<id_token>")]
async fn download(
    file_center: &State<FileCenter>,
    id_token: String,
) -> Result<Option<FileCenterDownloadResponse>, Status> {
    let object_id =
        file_center.decrypt_id_token(&id_token).map_err(|_| Status::InternalServerError)?;

    FileCenterDownloadResponse::from_object_id(file_center.inner(), object_id)
        .await
        .map_err(|_| Status::InternalServerError)
}

如果已经从文件中心拿到 FileItem 了,可以使用 FileCenterDownloadResponse 结构体的 from_file_item 关联函数来产生 FileCenterDownloadResponse 结构实体,如下:

#[get("/<id_token>")]
async fn download(
    file_center: &State<FileCenter>,
    id_token: String,
) -> Result<Option<FileCenterDownloadResponse>, Status> {
    let object_id =
        file_center.decrypt_id_token(&id_token).map_err(|_| Status::InternalServerError)?;

    let file_item = file_center
        .get_file_item_by_id(object_id)
        .await
        .map_err(|_| Status::InternalServerError)?;

    match file_item {
        Some(file_item) => Ok(Some(FileCenterDownloadResponse::from_file_item(file_item))),
        None => Ok(None),
    }
}