標籤:style blog http color os 使用 io for ar
1.不管是儲存普通資料也好,還是隱藏檔也好,我們都要先訪問MongoDB資料庫
public static MongoDatabase GetDataBase() { //MongoDB 伺服器位址 var client = new MongoClient(Config.BasicConfig.DbAddress); var server = client.GetServer(); //MongoDb 資料庫名稱 return server.GetDatabase(Config.BasicConfig.DbName); }
View Code
2:取得Fs
MongoDB擷取fs的執行個體我知道的有兩種寫法
- 1:直接通過 DataBase的屬性調用,如果我們把MongoDB理解成Sqlserver資料庫的話,那麼這種方式就是獲得到預設表“fs”的執行個體。
- 2:通過MongoGridFSSettings設定Root屬性值,MongoDB會根據Root的值,來產生具體的表,不需要自己建立
不說廢話,看代碼
//訪問一個名為test的檔案集合或表,如果沒有,則自動建立DbHelper.GetDataBase().GetGridFS(new MongoGridFSSettings { Root = "Test"});//擷取預設的集合或表“fs”DbHelper.GetDataBase().GridFS;
View Code
3:實現檔案上傳
檔案上傳時,MongoDB提供了一個MongoGridFSCreateOptions類,來完善我們的檔案資訊,我一般僅僅使用裡邊的ContentType
//huo de wen jian ji hevar fs = DbHelper.GetDataBase().GetGridFS(new MongoGridFSSettings { Root = fileType });//chuang jian wen jian shu xing , zhi jie shang chuan de wen jian mei you ContentType shu xing , xu yao shou dong zhi dingvar op = new MongoDB.Driver.GridFS.MongoGridFSCreateOptions { ContentType = contentType };//wen jian shang chuanvar fileInfo = fs.Upload(stream, filename, op);
View Code
4:檔案擷取
我在使用MongoDB fs的時候,我利用程式來控制檔案的名稱唯一,擷取的代碼
//擷取檔案 public FileItem GetFile(string fileNo, string fileType) { //組裝檔案名稱 var filename = string.Format("{0}_{1}", fileType, fileNo); var fs = DbHelper.GetDataBase().GetGridFS(new MongoGridFSSettings { Root = fileType }); //根據檔案名稱,尋找檔案 var fileInfo = fs.FindOne(filename); if (fileInfo != null && fileInfo.Exists) { using (var fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read)) { var bytes = new byte[fileStream.Length]; //讀取檔案為bytes fileStream.Read(bytes, 0, bytes.Length); return new FileItem { ContentType = fileInfo.ContentType, FileContent = bytes, Filename = fileInfo.Name, MD5 = fileInfo.MD5, Size = fileInfo.Length + "", UploadDate = fileInfo.UploadDate }; } } return null; }
View Code
5:檔案修改
檔案修改我就不說廢話了,直接看代碼就好了
//修改檔案(覆蓋)public FileItem Upload(string fileNo, string fileType, Stream stream) { var filename = string.Format("{0}_{1}", fileType, fileNo); var fs = DbHelper.GetDataBase().GetGridFS(new MongoGridFSSettings { Root = fileType }); var oldFileInfo = fs.FindOne(filename); if (oldFileInfo != null && oldFileInfo.Exists) { var bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); using (var sw = oldFileInfo.OpenWrite()) { sw.Seek(0, SeekOrigin.Begin); sw.Write(bytes, 0, bytes.Length); sw.Flush(); oldFileInfo.Refresh(); } } return new FileItem { ContentType = oldFileInfo.ContentType, FileContent = null, Filename = oldFileInfo.Name, MD5 = oldFileInfo.MD5, Size = oldFileInfo.Length + "", UploadDate = oldFileInfo.UploadDate }; }
View Code
寫的好不好不重要,重要的是可以跟有需要的人提供一個參考,也希望大神補充幾句,讓大家更方便。
MongoDB 檔案(MongoDB fs)