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); }
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;
3:实现文件上传
文件上传时,MongoDB提供了一个MongoGridFSCreateOptions类,来完善我们的文件信息,我一般仅仅使用里边的ContentType
//huo de wen jian ji he var 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 ding var op = new MongoDB.Driver.GridFS.MongoGridFSCreateOptions { ContentType = contentType }; //wen jian shang chuan var fileInfo = fs.Upload(stream, filename, op);
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; }
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 }; }
写的好不好不重要,重要的是可以跟有需要的人提供一个参考,也希望大神补充几句,让大家更方便。
时间: 2024-10-05 11:07:42