Program.cs代码如下:

  1. internal class Program
  2. {
  3. private static void Main(string[] args)
  4. {
  5. GridFSHelper helper = new GridFSHelper("mongodb://localhost", "GridFSDemo", "Pictures");
  6. #region 上传图片
  7. //第一种
  8. //Image image = Image.FromFile("D:\\dog.jpg");
  9. //byte[] imgdata = ImageHelper.ImageToBytes(image);
  10. //ObjectId oid = helper.UploadGridFSFromBytes(imgdata);
  11. //第二种
  12. //Image image = Image.FromFile("D:\\man.jpg");
  13. //Stream imgSteam = ImageHelper.ImageToStream(image);
  14. //ObjectId oid = helper.UploadGridFSFromStream("man",imgSteam);
  15. //LogHelper.WriteFile(oid.ToString());
  16. // Console.Write(oid.ToString());
  17. #endregion
  18. #region 下载图片
  19. //第一种
  20. //ObjectId downId = new ObjectId("578e2d17d22aed1850c7855d");
  21. //byte[] Downdata=  helper.DownloadAsByteArray(downId);
  22. //string name=  ImageHelper.CreateImageFromBytes("coolcar",Downdata);
  23. //第二种
  24. // byte[] Downdata = helper.DownloadAsBytesByName("QQQ");
  25. //string name = ImageHelper.CreateImageFromBytes("dog", Downdata);
  26. //第三种
  27. //byte[] Downdata = helper.DownloadAsBytesByName("QQQ");
  28. //Image img = ImageHelper.BytesToImage(Downdata);
  29. //string path = Path.GetFullPath(@"../../DownLoadImg/") + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
  30. ////使用path获取当前应用程序集的执行目录的上级的上级目录
  31. //img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
  32. #endregion
  33. #region 查找图片
  34. GridFSFileInfo gridFsFileInfo = helper.FindFiles("man");
  35. Console.WriteLine(gridFsFileInfo.Id);
  36. #endregion
  37. #region 删除图片
  38. //helper.DroppGridFSBucket();
  39. #endregion
  40. Console.ReadKey();
  41. }
  42. }

GridFSHelper.cs的代码如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using MongoDB.Bson;
  9. using MongoDB.Driver;
  10. using MongoDB.Driver.GridFS;
  11. namespace MongoDemo
  12. {
  13. public class GridFSHelper
  14. {
  15. private readonly IMongoClient client;
  16. private readonly IMongoDatabase database;
  17. private readonly IMongoCollection<BsonDocument> collection;
  18. private readonly GridFSBucket bucket;
  19. private GridFSFileInfo fileInfo;
  20. private ObjectId oid;
  21. public GridFSHelper()
  22. : this(
  23. ConfigurationManager.AppSettings["mongoQueueUrl"], ConfigurationManager.AppSettings["mongoQueueDb"],
  24. ConfigurationManager.AppSettings["mongoQueueCollection"])
  25. {
  26. }
  27. public GridFSHelper(string url, string db, string collectionName)
  28. {
  29. if (url == null)
  30. {
  31. throw new ArgumentNullException("url");
  32. }
  33. else
  34. {
  35. client = new MongoClient(url);
  36. }
  37. if (db == null)
  38. {
  39. throw new ArgumentNullException("db");
  40. }
  41. else
  42. {
  43. database = client.GetDatabase(db);
  44. }
  45. if (collectionName == null)
  46. {
  47. throw new ArgumentNullException("collectionName");
  48. }
  49. else
  50. {
  51. collection = database.GetCollection<BsonDocument>(collectionName);
  52. }
  53. //this.collection = new MongoClient(url).GetDatabase(db).GetCollection<BsonDocument>(collectionName);
  54. GridFSBucketOptions gfbOptions = new GridFSBucketOptions()
  55. {
  56. BucketName = "bird",
  57. ChunkSizeBytes = 1*1024*1024,
  58. ReadConcern = null,
  59. ReadPreference = null,
  60. WriteConcern = null
  61. };
  62. var bucket = new GridFSBucket(database, new GridFSBucketOptions
  63. {
  64. BucketName = "videos",
  65. ChunkSizeBytes = 1048576, // 1MB
  66. WriteConcern = WriteConcern.WMajority,
  67. ReadPreference = ReadPreference.Secondary
  68. });
  69. this.bucket = new GridFSBucket(database, null);
  70. }
  71. public GridFSHelper(IMongoCollection<BsonDocument> collection)
  72. {
  73. if (collection == null)
  74. {
  75. throw new ArgumentNullException("collection");
  76. }
  77. this.collection = collection;
  78. this.bucket = new GridFSBucket(collection.Database);
  79. }
  80. public ObjectId UploadGridFSFromBytes(string filename, Byte[] source)
  81. {
  82. oid = bucket.UploadFromBytes(filename, source);
  83. return oid;
  84. }
  85. public ObjectId UploadGridFSFromStream(string filename,Stream source)
  86. {
  87. using (source)
  88. {
  89. oid = bucket.UploadFromStream(filename, source);
  90. return oid;
  91. }
  92. }
  93. public Byte[] DownloadAsByteArray(ObjectId id)
  94. {
  95. Byte[] bytes = bucket.DownloadAsBytes(id);
  96. return bytes;
  97. }
  98. public Stream DownloadToStream(ObjectId id)
  99. {
  100. Stream destination = new MemoryStream();
  101. bucket.DownloadToStream(id, destination);
  102. return destination;
  103. }
  104. public Byte[] DownloadAsBytesByName(string filename)
  105. {
  106. Byte[] bytes = bucket.DownloadAsBytesByName(filename);
  107. return bytes;
  108. }
  109. public Stream DownloadToStreamByName(string filename)
  110. {
  111. Stream destination = new MemoryStream();
  112. bucket.DownloadToStreamByName(filename, destination);
  113. return destination;
  114. }
  115. public GridFSFileInfo FindFiles(string filename)
  116. {
  117. var filter = Builders<GridFSFileInfo>.Filter.And(
  118. Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, "man"),
  119. Builders<GridFSFileInfo>.Filter.Gte(x => x.UploadDateTime, new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc)),
  120. Builders<GridFSFileInfo>.Filter.Lt(x => x.UploadDateTime, new DateTime(2017, 2, 1, 0, 0, 0, DateTimeKind.Utc)));
  121. var sort = Builders<GridFSFileInfo>.Sort.Descending(x => x.UploadDateTime);
  122. var options = new GridFSFindOptions
  123. {
  124. Limit = 1,
  125. Sort = sort
  126. };
  127. using (var cursor = bucket.Find(filter, options))
  128. {
  129. fileInfo = cursor.ToList().FirstOrDefault();
  130. }
  131. return fileInfo;
  132. }
  133. public void DeleteAndRename(ObjectId id)
  134. {
  135. bucket.Delete(id);
  136. }
  137. //The “fs.files” collection will be dropped first, followed by the “fs.chunks” collection. This is the fastest way to delete all files stored in a GridFS bucket at once.
  138. public void DroppGridFSBucket()
  139. {
  140. bucket.Drop();
  141. }
  142. public void RenameAsingleFile(ObjectId id,string newFilename)
  143. {
  144. bucket.Rename(id, newFilename);
  145. }
  146. public void RenameAllRevisionsOfAfile(string oldFilename,string newFilename)
  147. {
  148. var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, oldFilename);
  149. var filesCursor = bucket.Find(filter);
  150. var files = filesCursor.ToList();
  151. foreach (var file in files)
  152. {
  153. bucket.Rename(file.Id, newFilename);
  154. }
  155. }
  156. }
  157. }

ImageHelper.cs的代码如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace MongoDemo
  10. {
  11. public static class ImageHelper
  12. {
  13. /// <summary>
  14. /// //将Image转换成流数据,并保存为byte[]
  15. /// </summary>
  16. /// <param name="image"></param>
  17. /// <returns></returns>
  18. public static byte[] ImageToBytes(Image image)
  19. {
  20. ImageFormat format = image.RawFormat;
  21. using (MemoryStream ms = new MemoryStream())
  22. {
  23. if (format.Equals(ImageFormat.Jpeg))
  24. {
  25. image.Save(ms, ImageFormat.Jpeg);
  26. }
  27. else if (format.Equals(ImageFormat.Png))
  28. {
  29. image.Save(ms, ImageFormat.Png);
  30. }
  31. else if (format.Equals(ImageFormat.Bmp))
  32. {
  33. image.Save(ms, ImageFormat.Bmp);
  34. }
  35. else if (format.Equals(ImageFormat.Gif))
  36. {
  37. image.Save(ms, ImageFormat.Gif);
  38. }
  39. else if (format.Equals(ImageFormat.Icon))
  40. {
  41. image.Save(ms, ImageFormat.Icon);
  42. }
  43. byte[] buffer = new byte[ms.Length];
  44. //Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin
  45. ms.Seek(0, SeekOrigin.Begin);
  46. ms.Read(buffer, 0, buffer.Length);
  47. return buffer;
  48. }
  49. }
  50. public static Stream ImageToStream(Image image)
  51. {
  52. ImageFormat format = image.RawFormat;
  53. MemoryStream ms = new MemoryStream();
  54. if (format.Equals(ImageFormat.Jpeg))
  55. {
  56. image.Save(ms, ImageFormat.Jpeg);
  57. }
  58. else if (format.Equals(ImageFormat.Png))
  59. {
  60. image.Save(ms, ImageFormat.Png);
  61. }
  62. else if (format.Equals(ImageFormat.Bmp))
  63. {
  64. image.Save(ms, ImageFormat.Bmp);
  65. }
  66. else if (format.Equals(ImageFormat.Gif))
  67. {
  68. image.Save(ms, ImageFormat.Gif);
  69. }
  70. else if (format.Equals(ImageFormat.Icon))
  71. {
  72. image.Save(ms, ImageFormat.Icon);
  73. }
  74. return ms;
  75. }
  76. //参数是图片的路径
  77. public static byte[] GetPictureData(string imagePath)
  78. {
  79. FileStream fs = new FileStream(imagePath, FileMode.Open);
  80. byte[] byteData = new byte[fs.Length];
  81. fs.Read(byteData, 0, byteData.Length);
  82. fs.Close();
  83. return byteData;
  84. }
  85. /// <summary>
  86. /// Convert Byte[] to Image
  87. /// </summary>
  88. /// <param name="buffer"></param>
  89. /// <returns></returns>
  90. public static Image BytesToImage(byte[] buffer)
  91. {
  92. MemoryStream ms = new MemoryStream(buffer);
  93. Image image = System.Drawing.Image.FromStream(ms);
  94. return image;
  95. }
  96. /// <summary>
  97. /// Convert Byte[] to a picture and Store it in file
  98. /// </summary>
  99. /// <param name="fileName"></param>
  100. /// <param name="buffer"></param>
  101. /// <returns></returns>
  102. public static string CreateImageFromBytes(string fileName, byte[] buffer)
  103. {
  104. string file = fileName;
  105. Image image = BytesToImage(buffer);
  106. ImageFormat format = image.RawFormat;
  107. if (format.Equals(ImageFormat.Jpeg))
  108. {
  109. file += ".jpg";
  110. }
  111. else if (format.Equals(ImageFormat.Png))
  112. {
  113. file += ".png";
  114. }
  115. else if (format.Equals(ImageFormat.Bmp))
  116. {
  117. file += ".bmp";
  118. }
  119. else if (format.Equals(ImageFormat.Gif))
  120. {
  121. file += ".gif";
  122. }
  123. else if (format.Equals(ImageFormat.Icon))
  124. {
  125. file += ".icon";
  126. }
  127. System.IO.FileInfo info = new System.IO.FileInfo(Path.GetFullPath(@"DownLoadImg\"));   //在当前程序集目录中添加指定目录DownLoadImg
  128. System.IO.Directory.CreateDirectory(info.FullName);
  129. File.WriteAllBytes(info+file, buffer);
  130. return file;
  131. }
  132. }
  133. }

LogHelper.cs代码如下:

  1. /// <summary>
  2. /// 手动记录错误日志,不用Log4Net组件
  3. /// </summary>
  4. public class LogHelper
  5. {
  6. /// <summary>
  7. ///  将日志写入指定的文件
  8. /// </summary>
  9. /// <param name="Path">文件路径,如果没有该文件,刚创建</param>
  10. /// <param name="content">日志内容</param>
  11. public static void WriteFile(string content)
  12. {
  13. string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";
  14. if (!Directory.Exists(Path))
  15. {
  16. //若文件目录不存在 则创建
  17. Directory.CreateDirectory(Path);
  18. }
  19. Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";
  20. if (!File.Exists(Path))
  21. {
  22. File.Create(Path).Close();
  23. }
  24. StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));
  25. writer.WriteLine("时间:" + DateTime.Now.ToString());
  26. writer.WriteLine("日志信息:" + content);
  27. writer.WriteLine("-----------------------------------------------------------");
  28. writer.Close();
  29. writer.Dispose();
  30. }
  31. /// <summary>
  32. ///  将日志写入指定的文件
  33. /// </summary>
  34. /// <param name="Path">文件路径,如果没有该文件,刚创建</param>
  35. /// <param name="content">日志内容</param>
  36. public static void WriteFile(int content)
  37. {
  38. string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";
  39. if (!Directory.Exists(Path))
  40. {
  41. //若文件目录不存在 则创建
  42. Directory.CreateDirectory(Path);
  43. }
  44. Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";
  45. if (!File.Exists(Path))
  46. {
  47. File.Create(Path).Close();
  48. }
  49. StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));
  50. writer.WriteLine("时间:" + DateTime.Now.ToString());
  51. writer.WriteLine("日志信息:" + content);
  52. writer.WriteLine("-----------------------------------------------------------");
  53. writer.Close();
  54. writer.Dispose();
  55. }
  56. /// <summary>
  57. ///  将日志写入指定的文件
  58. /// </summary>
  59. /// <param name="erroMsg">错误详细信息</param>
  60. /// <param name="source">源位置</param>
  61. /// <param name="fileName">文件名</param>
  62. public static void WriteFile(string erroMsg, string source, string stackTrace, string fileName)
  63. {
  64. string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";
  65. if (!Directory.Exists(Path))
  66. {
  67. //若文件目录不存在 则创建
  68. Directory.CreateDirectory(Path);
  69. }
  70. Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";
  71. if (!File.Exists(Path))
  72. {
  73. File.Create(Path).Close();
  74. }
  75. StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));
  76. writer.WriteLine("时间:" + DateTime.Now.ToString());
  77. writer.WriteLine("文件:" + fileName);
  78. writer.WriteLine("源:" + source);
  79. writer.WriteLine("错误信息:" + erroMsg);
  80. writer.WriteLine("-----------------------------------------------------------");
  81. writer.Close();
  82. writer.Dispose();
  83. }
  84. }

结果如下:

Mongodb数据:

查找图片:

使用MongoDB.NET 2.2.4驱动版本对 Mongodb3.3数据库中GridFS增删改查的更多相关文章

  1. 十四:SpringBoot-配置MongoDB数据库,实现增删改查逻辑

    SpringBoot-配置MongoDB数据库,实现增删改查逻辑 1.MongoDB数据库 1.1 MongoDB简介 1.2 MongoDB特点 2.SpringBoot整合MongoDB 2.1 ...

  2. MongoDB 基础命令——数据库表的增删改查——遍历操作表中的记录

    分组排序查询最大记录 //对 "catagory" 不等于 null 的数据进行分组查询,且查询结果倒序 db.getCollection('userAccount').aggre ...

  3. SpringBoot2.0 基础案例(15):配置MongoDB数据库,实现增删改查逻辑

    本文源码:GitHub·点这里 || GitEE·点这里 一.NoSQL简介 1.NoSQL 概念 NoSQL( Not Only SQL ),意即"不仅仅是SQL".对不同于传统 ...

  4. MongoDB增删改查表文档

    MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写,是一个基于分布式文件存储的开源数据库系统.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关 ...

  5. Mongodb c#增删改查

    写在前面 最近项目需要,就研究了下mongodb,也是为了快速上手,就自己弄了一个简单的例子,这里记录一下. Mongodb 传统的关系数据库一般由数据库(database).表(table).记录( ...

  6. nodejs笔记五--MongoDB基本环境配置及增删改查;

    一.基本环境配置: 1,首先到官网(http://www.mongodb.org/downloads )下载合适的安装包,然后一步一步next安装,当然可以自己更改安装目录:安装完成之后,配置环境变量 ...

  7. 大数据之路week05--day01(JDBC 初识之实现一个系统 实现用户选择增删改查 未优化版本)

    要求,实现用户选择增删改查. 给出mysql文件,朋友们可以自己运行导入到自己的数据库中: /* Navicat MySQL Data Transfer Source Server : mysql S ...

  8. MongoDB学习-->命令行增删改查&JAVA驱动操作Mongodb

    MongoDB 是一个基于分布式文件存储的数据库. 由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关 ...

  9. mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)

    最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...

随机推荐

  1. Parallel Database for OLTP and OLAP

    Parallel Database for OLTP and OLAP Just asurvey article on materials on parallel database products ...

  2. "visual studio 2012 安装引擎拒绝访问" 错误的解决

    首先,我们看一下错误的具体提示,如下图所示: 这个错误,是我安装了那么多年Visual Studio的经历中,第一次遇到.太恶心了,昨天一直安装失败,导致后续其它软件的安装一再拖延.目前网上的解决方案 ...

  3. 类加载器在加载类 的时候就已经对类的static代码块和static变量进行了初始化

    类装载器ClassLoader 类装载器工作机制 类装载器就是寻找类的节码文件并构造出类在JVM内部表示对象的组件.在Java中,类装载器把一个类装入JVM中,要经过以下步骤: [1.]装载:查找和导 ...

  4. spoj 1811 LCS - Longest Common Substring (后缀自己主动机)

    spoj 1811 LCS - Longest Common Substring 题意: 给出两个串S, T, 求最长公共子串. 限制: |S|, |T| <= 1e5 思路: dp O(n^2 ...

  5. Android自己定义View的实现方法

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/17357967 不知不觉中,带你一步步深入了解View系列的文章已经写到第四篇了.回 ...

  6. ActiveMQ测试工具

    1. 测试工具 目前使用两种测试工具进行压力测试 1. Jmeter 测试单客户端收发多主题,测试高并发,大数据量时的接收效率 2. emqtt_benchmark测试多客户端收发主题,测试高吞吐量下 ...

  7. SharePoint ULS Log Viewer 日志查看器

    SharePoint ULS Log Viewer 日志查看器 项目描写叙述 这是一个Windows应用程序,更加轻松方便查看SharePoint ULS日志文件.支持筛选和简单的视图. 信息 这是一 ...

  8. React项目结构

    任何一种语言.框架,在真正上手的时候,多多少少会想想怎么安排项目结构(正所谓磨刀不误砍柴工),React也不例外. google了下,拿下面3篇博客来说道说道. (1) how-to-better-o ...

  9. MongoDB 征途

    到目前为止,对数据库这块仍然捉襟见肘,仅限于懂一些MySQL,就更谈不上什么优化了. 细想来,还是没有项目驱动造成的...既然跟关系型数据库缘分未到,干脆直接go to NoSQL - MongoDB ...

  10. JSP页面的编码设置(转载)

    1. pageEncoding:<%@ page pageEncoding="UTF-8"%> jsp页面编码: jsp文件本身的编码 2. contentType: ...