主頁 > .NET開發 > C# 玩轉MongoDB(三)

C# 玩轉MongoDB(三)

2021-10-13 06:04:54 .NET開發

前面兩篇文章,已經講解了C#對MongoDB的基本操作以及小檔案的讀寫存盤,那么對于大型(>=16M)檔案呢?具體又該如何操作呢,本文主要以一個簡單的小例子,簡述C#如何通過GridFS進行MongoDB的大檔案的操作,僅供學習分享使用,如有不足之處,還請指正,

什么是GridFS?

在實作GridFS方式前我先講講它的原理,為什么可以存大檔案,驅動首先會在當前資料庫創建兩個集合:"fs.files"和"fs.chunks"集合,前者記錄了檔案名,檔案創建時間,檔案型別等基本資訊;后者分塊存盤了檔案的二進制資料(并支持加密這些二進制資料),分塊的意思是把檔案按照指定大小分割,然后存入多個檔案中,"fs.files"怎么知道它對應的檔案二進制資料在哪些塊呢?那是因為在"fs.chunks"中有個"files_id"鍵,它對應"fs.files"的"_id","fs.chunks"還有一個鍵(int型)"n",它表明這些塊的先后順序,這兩個集合名中的"fs"也是可以通過引數自定義的,

GridFS存盤原理

一個檔案存盤在兩個集合中,一個用于存盤元資料(檔案名稱,型別,大小等內容,可便于索引),一個用于存盤真實二進制資料(分塊存盤),如下所示:

 

 GridFS安裝

如果需要存盤大型檔案,則需要安裝GridFS插件,如下所示:

專案--右鍵--管理Nuget程式包--打卡Nuget包管理器--瀏覽搜索MongoDB.Driver.GridFS--安裝,如下所示:

示例截圖

首先是檔案的查詢,如下所示:

檔案的新增

 

 核心代碼

本示例主要是在MongoDB中進行檔案的操作,所以之前的MongoHelper已不再適用,本例新增了檔案專用幫助類MongoFileHelper,如下所示:

  1 using MongoDB.Bson;
  2 using MongoDB.Driver;
  3 using MongoDB.Driver.GridFS;
  4 using System;
  5 using System.Collections.Generic;
  6 using System.IO;
  7 using System.Linq;
  8 using System.Text;
  9 using System.Threading.Tasks;
 10 
 11 namespace DemoMongo.Common
 12 {
 13 
 14     public class MongoFileHelper
 15     {
 16 
 17         private string connStr = "mongodb://127.0.0.1:27017";//服務器網址
 18 
 19         private string dbName = "hexdb";//資料庫名稱
 20 
 21         private IMongoClient client;//連接客戶端
 22 
 23         private IMongoDatabase db;//連接資料庫
 24 
 25         private string collName;//集合名稱
 26 
 27         public MongoFileHelper()
 28         {
 29 
 30         }
 31 
 32         public MongoFileHelper(string connStr, string dbName, string collName)
 33         {
 34             this.connStr = connStr;
 35             this.dbName = dbName;
 36             this.collName = collName;
 37             this.Init();
 38         }
 39 
 40         /// <summary>
 41         /// 初始化連接客戶端
 42         /// </summary>
 43         private void Init()
 44         {
 45             if (client == null)
 46             {
 47                 client = new MongoClient(this.connStr);
 48             }
 49             if (db == null)
 50             {
 51                 db = client.GetDatabase(this.dbName);
 52             }
 53         }
 54 
 55         /// <summary>
 56         /// 通過位元組方式上傳
 57         /// </summary>
 58         /// <param name="filePath"></param>
 59         public void UploadFile(string filePath)
 60         {
 61             IGridFSBucket bucket = new GridFSBucket(db);
 62             byte[] source = File.ReadAllBytes(filePath);
 63             string fileName = Path.GetFileName(filePath);
 64             var options = new GridFSUploadOptions
 65             {
 66                 ChunkSizeBytes = 64512, // 63KB
 67                 Metadata = https://www.cnblogs.com/hsiang/archive/2021/10/12/new BsonDocument
 68                 {
 69                     { "resolution", "1080P" },
 70                     { "copyrighted", true }
 71                 }
 72             };
 73             var id = bucket.UploadFromBytes(fileName, source);
 74             //回傳的ID,表示檔案的唯一ID
 75 
 76 
 77         }
 78 
 79         /// <summary>
 80         /// 通過Stream方式上傳
 81         /// </summary>
 82         /// <param name="filePath"></param>
 83         public void UploadFile2(string filePath)
 84         {
 85             IGridFSBucket bucket = new GridFSBucket(db);
 86             var stream = new FileStream(filePath, FileMode.Open);
 87 
 88             string fileName = Path.GetFileName(filePath);
 89             var options = new GridFSUploadOptions
 90             {
 91                 ChunkSizeBytes = 64512, // 63KB
 92                 Metadata = https://www.cnblogs.com/hsiang/archive/2021/10/12/new BsonDocument
 93                 {
 94                     { "resolution", "1080P" },
 95                     { "copyrighted", true }
 96                 }
 97             };
 98             var id = bucket.UploadFromStream(fileName, stream);
 99             //回傳的ID,表示檔案的唯一ID
100 
101 
102         }
103 
104         /// <summary>
105         /// 通過位元組寫入到流
106         /// </summary>
107         /// <param name="filePath"></param>
108         public void UploadFile3(string filePath)
109         {
110             IGridFSBucket bucket = new GridFSBucket(db);
111             byte[] source = File.ReadAllBytes(filePath);
112             string fileName = Path.GetFileName(filePath);
113             var options = new GridFSUploadOptions
114             {
115                 ChunkSizeBytes = 64512, // 63KB
116                 Metadata = https://www.cnblogs.com/hsiang/archive/2021/10/12/new BsonDocument
117                 {
118                     { "resolution", "1080P" },
119                     { "copyrighted", true }
120                 }
121             };
122             using (var stream = bucket.OpenUploadStream(fileName, options))
123             {
124                 var id = stream.Id;
125                 stream.Write(source, 0, source.Length);
126                 stream.Close();
127             }
128         }
129 
130         /// <summary>
131         /// 下載檔案
132         /// </summary>
133         /// <param name="id"></param>
134         public void DownloadFile(ObjectId id,string filePath)
135         {
136             IGridFSBucket bucket = new GridFSBucket(db);
137             byte[] source = bucket.DownloadAsBytes(id);
138             //回傳的位元組內容
139             //var bytes = await bucket.DownloadAsBytesAsync(id);
140             using (Stream stream = new FileStream(filePath, FileMode.OpenOrCreate)) {
141                 stream.Write(source, 0, source.Length);
142             }
143         }
144 
145         public void DownloadFile2(ObjectId id)
146         {
147             IGridFSBucket bucket = new GridFSBucket(db);
148             Stream destination = null;
149             bucket.DownloadToStream(id, destination);
150             //回傳的位元組內容
151             //await bucket.DownloadToStreamAsync(id, destination);
152 
153         }
154 
155         public void DownloadFile3(ObjectId id)
156         {
157             IGridFSBucket bucket = new GridFSBucket(db);
158             Stream destination = null;
159             using (var stream = bucket.OpenDownloadStream(id))
160             {
161                 // read from stream until end of file is reached
162                 stream.Close();
163             }
164         }
165 
166         public void DownloadFile4(string fileName)
167         {
168             IGridFSBucket bucket = new GridFSBucket(db);
169             var bytes = bucket.DownloadAsBytesByName(fileName);
170 
171             // or
172 
173             Stream destination = null;
174             bucket.DownloadToStreamByName(fileName, destination);
175 
176             // or
177 
178             using (var stream = bucket.OpenDownloadStreamByName(fileName))
179             {
180                 // read from stream until end of file is reached
181                 stream.Close();
182             }
183         }
184 
185         public List<MongoFile> FindFiles()
186         {
187             IGridFSBucket bucket = new GridFSBucket(db);
188             var filter = Builders<GridFSFileInfo>.Filter.And(
189                 //Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, string.Empty),
190                 Builders<GridFSFileInfo>.Filter.Gte(x => x.UploadDateTime, new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc)),
191                 Builders<GridFSFileInfo>.Filter.Lt(x => x.UploadDateTime, new DateTime(2022, 2, 1, 0, 0, 0, DateTimeKind.Utc)));
192             var sort = Builders<GridFSFileInfo>.Sort.Descending(x => x.UploadDateTime);
193             var options = new GridFSFindOptions
194             {
195                 //Limit = 1,
196                 Sort = sort
197             };
198             List<MongoFile> lstFiles = new List<MongoFile>();
199             using (var cursor = bucket.Find(filter, options))
200             {
201                 var fileInfos = cursor.ToList();
202                 foreach (var fileInfo in fileInfos) {
203                     MongoFile f = new MongoFile()
204                     {
205                          Id=fileInfo.Id,
206                          name = fileInfo.Filename,
207                          suffix = Path.GetExtension(fileInfo.Filename),
208                         size = int.Parse(fileInfo.Length.ToString())
209                     };
210                     lstFiles.Add(f);
211                 }
212             }
213             return lstFiles;
214         }
215 
216         public List<MongoFile> FindFileByName(string fileName)
217         {
218             IGridFSBucket bucket = new GridFSBucket(db);
219             var filter = Builders<GridFSFileInfo>.Filter.And(
220                 Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, fileName),
221                 Builders<GridFSFileInfo>.Filter.Gte(x => x.UploadDateTime, new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc)),
222                 Builders<GridFSFileInfo>.Filter.Lt(x => x.UploadDateTime, new DateTime(2015, 2, 1, 0, 0, 0, DateTimeKind.Utc)));
223             var sort = Builders<GridFSFileInfo>.Sort.Descending(x => x.UploadDateTime);
224             var options = new GridFSFindOptions
225             {
226                 //Limit = 1,
227                 Sort = sort
228             };
229             List<MongoFile> lstFiles = new List<MongoFile>();
230             using (var cursor = bucket.Find(filter, options))
231             {
232                 var fileInfos = cursor.ToList();
233                 foreach (var fileInfo in fileInfos)
234                 {
235                     MongoFile f = new MongoFile()
236                     {
237                         Id = fileInfo.Id,
238                         name = fileInfo.Filename,
239                         suffix = Path.GetExtension(fileInfo.Filename),
240                         size = int.Parse(fileInfo.Length.ToString())
241                     };
242                     lstFiles.Add(f);
243                 }
244             }
245             return lstFiles;
246         }
247     }
248 }

然后操作時,呼叫幫助類即可,如下所示:

查詢呼叫

 1        private void btnQuery_Click(object sender, EventArgs e)
 2         {
 3             string name = this.txtName.Text.Trim();
 4             List<MongoFile> fileInfos = new List<MongoFile>();
 5             if (string.IsNullOrEmpty(name))
 6             {
 7                 fileInfos = helper.FindFiles();
 8             }
 9             else {
10                 fileInfos = helper.FindFileByName(name);
11             }
12             
13             this.dgView.AutoGenerateColumns = false;
14             this.bsView.DataSource = fileInfos;
15             this.dgView.DataSource = this.bsView;
16         }

下載呼叫

 1         private void dgView_CellContentClick(object sender, DataGridViewCellEventArgs e)
 2         {
 3             if (e.ColumnIndex == 3) {
 4                 //第3個是下載按鈕
 5                 SaveFileDialog sfd = new SaveFileDialog();
 6                 
 7                 var file = (MongoFile)(this.dgView.Rows[e.RowIndex].DataBoundItem);
 8                 sfd.FileName = file.name;
 9                 sfd.Title = "請保存檔案";
10                 if (DialogResult.OK == sfd.ShowDialog())
11                 {
12                     helper.DownloadFile(file.Id,sfd.FileName);
13                     MessageBox.Show("保存成功");
14 
15                 }
16             }
17         }

保存呼叫

 1         private void btnSave_Click(object sender, EventArgs e)
 2         {
 3             string filePath = this.txtPath.Text;
 4             if (!string.IsNullOrEmpty(filePath))
 5             {
 6                 this.helper.UploadFile(filePath);
 7                 MessageBox.Show("保存成功");
 8             }
 9             else {
10                 MessageBox.Show("請先選擇檔案");
11             }
12             
13         }

MongoDB查詢

當通過GridFS方式保存檔案成功后,會在GridFS Buckets下生成fs物件,且在集合下生成兩個集合【fs.files,fs.chunks】,用于存盤檔案,如下所示:

 

 通過查詢fs.files集合,可以查找上傳檔案的串列,如下所示:

 

 通過查詢fs.chunks集合,可以查詢檔案的內容(二進制資料),如下所示:

 

 注意:如果檔案太大,在fs.chunks集合中,進行分片存盤,n表示存盤的順序,

 以上就是C#操作MongoDB大檔案存盤的相關內容,旨在拋磚引玉,共同進步,

備注

點絳唇·感興

【朝代】宋代 【作者】王禹偁【chēng】

雨恨云愁,江南依舊稱佳麗,水村漁市,一縷孤煙細,
天際征鴻,遙認行如綴,平生事,此時凝睇,誰會憑欄意,(欄 通:闌)


作者:Alan.hsiang
出處:http://www.cnblogs.com/hsiang/
本文著作權歸作者和博客園共有,寫文不易,支持原創,歡迎轉載【點贊】,轉載請保留此段宣告,且在文章頁面明顯位置給出原文連接,謝謝,
關注個人公眾號,定時同步更新技術及職場文章

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/310332.html

標籤:.NET技术

上一篇:學習使用Wpf開源的文本編輯器—smithhtmleditor

下一篇:安卓11存盤訪問和Java檔案庫

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more