在先前的文章中,我們介紹了能讓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)和檔案名稱(如果不設定則使用檔案中心儲存的檔案名稱)。
以下是一個完整的例子:
#[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::{EtagIfNoneMatch, FileCenterDownloadResponse};
use rocket::http::Status;
use rocket::State;
const URL: &str = "mongodb://localhost:27017";
#[get("/<id_token>")]
async fn download(
etag_if_none_match: &EtagIfNoneMatch<'_>,
file_center: &State<FileCenter>,
id_token: String,
) -> Result<Option<FileCenterDownloadResponse>, Status> {
FileCenterDownloadResponse::from_id_token(
file_center.inner(),
etag_if_none_match,
id_token,
None::<String>,
)
.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(())
}
程式一開始,會將工作目錄下的image.jpg這張JPEG圖檔儲存到檔案中心中,然後在螢幕上顯示出這筆加密過的Object ID(也就是「ID token」)。接著將檔案中心註冊給Rocket,並啟動Rocket。在download這個路由處理程序中,會讀取網址路徑中帶的ID token。(ShortCryptUrlComponent結構體來自於validators這個crate,有關於validators的介紹可以參考這篇文章。)from_id_token會根據這個ID token來查詢檔案中心裡對應的檔案,並回傳Result<Option<FileCenterDownloadResponse>, FileCenterError>,注意因為這邊的FileCenterError並沒有實作rocket::response::Responder特性,所以如果直接拿來回傳的話,等同於發生500錯誤。
如果是要用from_object_id關聯函數來建立FileCenterDownloadResponse結構實體,把以上的download路由處理程序用from_object_id關聯函數改寫的話就會變成以下這樣:
#[get("/<id_token>")]
async fn download(
etag_if_none_match: &EtagIfNoneMatch<'_>,
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 etag = FileCenterDownloadResponse::create_etag_by_id_token(id_token);
FileCenterDownloadResponse::from_object_id(
file_center.inner(),
Some(etag_if_none_match),
Some(etag),
object_id,
None::<String>,
)
.await
.map_err(|_| Status::InternalServerError)
}
如果已經從檔案中心拿到FileItem了,可以使用FileCenterDownloadResponse結構體的from_file_item關聯函數來產生FileCenterDownloadResponse結構實體,如下:
#[get("/<id_token>")]
async fn download(
etag_if_none_match: &EtagIfNoneMatch<'_>,
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 etag = FileCenterDownloadResponse::create_etag_by_id_token(id_token);
if etag_if_none_match.weak_eq(&etag) {
Err(Status::NotModified)
} else {
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(
Some(etag),
file_item,
None::<String>,
)))
}
None => Ok(None),
}
}
}

