在先前的文章中,我們介紹了能讓 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
使用方法
先將 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),
}
}
