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
83
|
#[derive(Debug, Serialize)]
pub struct GridFSDocumentInfo {
pub objectid: String,
pub filename: String,
pub chunk_size: i32,
pub length: i64,
pub upload_date: Option<DateTime>,
}
pub async fn find_file_in_gridfs(bucket: &mut GridFSBucket, file_name: &str, file_data: &Vec<u8>) -> Result<GridFSDocumentInfo, Box<dyn std::error::Error>> {
let mut cursor = bucket
.find(doc! {"filename":file_name}, GridFSFindOptions::default())
.await?;
let mut is_found = false;
let mut info = GridFSDocumentInfo{objectid: "".to_string(),
filename: "".to_string() ,
chunk_size: 0,
length: 0,
upload_date:None};
// 遍历 Cursor<Document> 并获取 Document 信息
while let Some(doc) = cursor.next().await {
match doc {
Ok(document) => {
// 处理查询到的文档
println!("Found document: {:?}", document);
if let Some(_id) = document.get("_id").and_then(|v| v.as_object_id()) {
println!("File objectid: {}", _id.to_hex());
info.objectid = _id.to_hex();
}
if let Some(file_name) = document.get("filename").and_then(|v| v.as_str()) {
println!("File Name: {}", file_name);
info.filename = file_name.to_string();
}
if let Some(chunk_size) = document.get("chunkSize").and_then(|v| v.as_i32()) {
println!("File chunkSize: {}", chunk_size);
info.chunk_size = chunk_size;
}
if let Some(length) = document.get("length").and_then(|v| v.as_i64()) {
println!("File length: {}", length);
info.length = length;
}
if let Some(upload_date) = document.get("uploadDate").and_then(|v| v.as_datetime()) {
println!("Upload Date: {}", upload_date);
info.upload_date = Some(*upload_date);
}
if let Some(length) = document.get("length").and_then(|v| v.as_i64()) {
println!("File Size: {} bytes", length);
}
if let Some(file_md5) = document.get("md5").and_then(|v| v.as_str()) {
println!("File md5:{}", file_md5);
let md5_string = md5_data(&file_data);
let result = md5_string.ok_or_else(||
actix_web::error::ErrorBadRequest("MD5 string is missing")
)?;
if result == file_md5 {
//actix_web::error::ErrorNotFound("MD5 not match")
is_found = true;
}
}
}
Err(err) => {
println!("Error while iterating cursor: {}", err);
return Err(Box::new(err));
}
}
}
if is_found {
Ok(info)
} else {
Err(Box::new(actix_web::error::ErrorNotFound("File not found")))
}
}
|