1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
pub extern crate mongo_file_center;
extern crate percent_encoding;
extern crate rocket;
use std::io::Cursor;
use mongo_file_center::{FileCenter, FileItem, FileData, FileCenterError, bson::oid::ObjectId};
use rocket::response::{self, Response, Responder};
use rocket::request::Request;
#[derive(Debug)]
pub struct FileCenterDownloadResponse {
pub file_item: FileItem,
pub file_name: Option<String>,
}
impl Responder<'static> for FileCenterDownloadResponse {
fn respond_to(self, _: &Request) -> response::Result<'static> {
let mut response = Response::build();
response.raw_header("Content-Transfer-Encoding", "binary");
let file_item = self.file_item;
if let Some(file_name) = self.file_name {
if file_name.is_empty() {
response.raw_header("Content-Disposition", "attachment");
} else {
response.raw_header("Content-Disposition", format!("attachment; filename*=UTF-8''{}", percent_encoding::percent_encode(file_name.as_bytes(), percent_encoding::QUERY_ENCODE_SET)));
}
} else {
let file_name = file_item.get_file_name();
if file_name.is_empty() {
response.raw_header("Content-Disposition", "attachment");
} else {
response.raw_header("Content-Disposition", format!("attachment; filename*=UTF-8''{}", percent_encoding::percent_encode(file_name.as_bytes(), percent_encoding::QUERY_ENCODE_SET)));
}
}
response.raw_header("Content-Type", file_item.get_mime_type().to_string())
.raw_header("Content-Length", file_item.get_file_size().to_string());
match file_item.into_file_data() {
FileData::Collection(v) => {
response.sized_body(Cursor::new(v));
}
FileData::GridFS(g) => {
response.streamed_body(g);
}
}
response.ok()
}
}
impl FileCenterDownloadResponse {
pub fn from_object_id<S: Into<String>>(file_center: &FileCenter, id: &ObjectId, file_name: Option<S>) -> Result<Option<FileCenterDownloadResponse>, FileCenterError> {
let file_item = file_center.get_file_item_by_id(id)?;
match file_item {
Some(file_item) => {
let file_name = file_name.map(|file_name| file_name.into());
Ok(Some(FileCenterDownloadResponse {
file_item,
file_name,
}))
}
None => Ok(None)
}
}
}