因爲MongoDB的文檔結構爲BJSON格式(BJSON全稱:Binary JSON),而BJSON格式自己就支持保存二進制格式的數據,所以能夠把文件的二進制格式的數據直接保存到MongoDB的文檔結構中。可是因爲一個BJSON的最大長度不能超過4M,因此限制了單個文檔中能存入的最大文件不能超過4M。爲了提供對大容量文件存取的支持,samus驅動提供了「GridFS」方式來支持,「GridFS」方式文件操做須要引入新的程序集「MongoDB.GridFS.dll」。下面咱們分別用兩種方式來實現。
1、在文檔對象中存取文件
當文件大小較小的時候,直接存入文檔對象實現起來更簡潔。好比大量圖片文件的存取等,通常圖片文件都不會超過4M。咱們先實現一個上傳圖片存入數據庫,再取出來寫回頁面的例子:html
1. 把圖片存到BJSON中web
04 |
public void SaveImgBJSON( byte [] byteImg) |
06 |
Document doc = new Document(); |
09 |
mongoCollection.Save(doc); |
2. 獲取BJSON方式存儲的圖片字節數據數據庫
4 |
public byte [] GetImgBJSON() |
6 |
Document doc= mongoCollection.FindOne( new Document { { "ID" , 1 } }); |
7 |
return doc[ "Img" ] as Binary; |
上面兩段代碼是在對MongoDB相關操做進行BLL封裝類中添加的兩個方法,封裝方式查看上節內容。下面看看在webform中如何調用:函數
在界面拖出一個FileUpload控件和一個Button控件,頁面cs類加以下方法:ui
1 |
protected void Button1_Click( object sender, EventArgs e) |
3 |
ImgBLL imgBll = new ImgBLL(); |
5 |
imgBll.SaveImgBJSON(FileUpload1.FileBytes); |
6 |
Response.BinaryWrite(imgBll.GetImgBJSON()); |
2、用GridFS方式存取文件
在實現GridFS方式前我先講講它的原理,爲何能夠存大文件。驅動首先會在當前數據庫建立兩個集合:"fs.files"和"fs.chunks"集合,前者記錄了文件名,文件建立時間,文件類型等基本信息;後者分塊存儲了文件的二進制數據(並支持加密這些二進制數據)。分塊的意思是把文件按照指定大小分割,而後存入多個文檔中。"fs.files"怎麼知道它對應的文件二進制數據在哪些塊呢?那是由於在"fs.chunks"中有個"files_id"鍵,它對應"fs.files"的"_id"。"fs.chunks"還有一個鍵(int型)"n",它代表這些塊的前後順序。這兩個集合名中的"fs"也是能夠經過參數自定義的。加密
若是你只是想知道怎麼用,能夠忽略上面這段話,下面將用法:spa
1. GridFS方式的文件新建,讀取,刪除code
01 |
private string GridFsSave( byte [] byteFile) |
03 |
string filename = Guid.NewGuid().ToString(); |
05 |
//這裏GridFile構造函數有個重載,bucket參數就是用來替換那個建立集合名中默認的"fs"的。 |
06 |
GridFile gridFile = new GridFile(mongoDatabase); |
07 |
using (GridFileStream gridFileStream = gridFile.Create(filename)) |
09 |
gridFileStream.Write(byteFile, 0, byteFile.Length); |
14 |
private byte [] GridFsRead( string filename) |
16 |
GridFile gridFile = new GridFile(mongoDatabase); |
17 |
GridFileStream gridFileStream = gridFile.OpenRead(filename); |
18 |
byte [] bytes = new byte [gridFileStream.Length]; |
19 |
gridFileStream.Read(bytes, 0, bytes.Length); |
23 |
private void GridFsDelete( string filename) |
25 |
GridFile gridFile = new GridFile(mongoDatabase); |
26 |
gridFile.Delete( new Document( "filename" , filename)); |
2. 再次封裝GridFS操做,新文檔只存儲文件名稱,至關於只是一個鍵,新文檔還能夠有除「文件名」以外其餘的鍵。orm
04 |
public void SaveImgGridFS( byte [] byteImg) |
06 |
string filename = GridFsSave(byteImg); |
08 |
Document doc = new Document(); |
10 |
doc[ "filename" ] = filename; |
11 |
mongoCollection.Save(doc); |
17 |
public byte [] GetImgGridFS() |
19 |
Document doc = mongoCollection.FindOne( new Document { { "ID" , 1 } }); |
20 |
string filename = doc[ "filename" ].ToString(); |
21 |
return GridFsRead(filename); |
3、小結
文件存取應該不是很難,值得注意的地方是:用第一種方式從文檔中讀出二進制數據時,必定要將類型轉換爲「Binary」類型;還有系統自帶的鍵「_id」,它也不是string類型,是「Oid」類型的。htm