侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

MongoDB.NET 2.2.4驱动版本对Mongodb3.3数据库中GridFS增删改查

数据库  /  管理员 发布于 6年前   158

本文实例为大家分享了针对Mongodb3.3数据库中GridFS增删改查,供大家参考,具体内容如下

Program.cs代码如下:

internal class Program  {   private static void Main(string[] args)   {    GridFSHelper helper = new GridFSHelper("mongodb://localhost", "GridFSDemo", "Pictures");     #region 上传图片     //第一种    //Image image = Image.FromFile("D:\\dog.jpg");    //byte[] imgdata = ImageHelper.ImageToBytes(image);    //ObjectId oid = helper.UploadGridFSFromBytes(imgdata);     //第二种    //Image image = Image.FromFile("D:\\man.jpg");    //Stream imgSteam = ImageHelper.ImageToStream(image);    //ObjectId oid = helper.UploadGridFSFromStream("man",imgSteam);    //LogHelper.WriteFile(oid.ToString());    // Console.Write(oid.ToString());     #endregion     #region 下载图片     //第一种    //ObjectId downId = new ObjectId("578e2d17d22aed1850c7855d");    //byte[] Downdata= helper.DownloadAsByteArray(downId);    //string name= ImageHelper.CreateImageFromBytes("coolcar",Downdata);     //第二种    // byte[] Downdata = helper.DownloadAsBytesByName("QQQ");    //string name = ImageHelper.CreateImageFromBytes("dog", Downdata);     //第三种    //byte[] Downdata = helper.DownloadAsBytesByName("QQQ");    //Image img = ImageHelper.BytesToImage(Downdata);    //string path = Path.GetFullPath(@"../../DownLoadImg/") + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";    ////使用path获取当前应用程序集的执行目录的上级的上级目录    //img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);     #endregion     #region 查找图片    GridFSFileInfo gridFsFileInfo = helper.FindFiles("man");    Console.WriteLine(gridFsFileInfo.Id);    #endregion     #region 删除图片    //helper.DroppGridFSBucket();    #endregion     Console.ReadKey();   }  } 

GridFSHelper.cs的代码如下:

using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.GridFS;  namespace MongoDemo {  public class GridFSHelper  {   private readonly IMongoClient client;   private readonly IMongoDatabase database;   private readonly IMongoCollection<BsonDocument> collection;   private readonly GridFSBucket bucket;   private GridFSFileInfo fileInfo;   private ObjectId oid;    public GridFSHelper()    : this(     ConfigurationManager.AppSettings["mongoQueueUrl"], ConfigurationManager.AppSettings["mongoQueueDb"],     ConfigurationManager.AppSettings["mongoQueueCollection"])   {   }    public GridFSHelper(string url, string db, string collectionName)   {    if (url == null)    {     throw new ArgumentNullException("url");    }    else    {     client = new MongoClient(url);    }     if (db == null)    {     throw new ArgumentNullException("db");    }    else    {     database = client.GetDatabase(db);    }     if (collectionName == null)    {     throw new ArgumentNullException("collectionName");    }    else    {     collection = database.GetCollection<BsonDocument>(collectionName);    }     //this.collection = new MongoClient(url).GetDatabase(db).GetCollection<BsonDocument>(collectionName);     GridFSBucketOptions gfbOptions = new GridFSBucketOptions()    {     BucketName = "bird",     ChunkSizeBytes = 1*1024*1024,     ReadConcern = null,     ReadPreference = null,     WriteConcern = null    };    var bucket = new GridFSBucket(database, new GridFSBucketOptions    {     BucketName = "videos",     ChunkSizeBytes = 1048576, // 1MB     WriteConcern = WriteConcern.WMajority,     ReadPreference = ReadPreference.Secondary    });    this.bucket = new GridFSBucket(database, null);   }    public GridFSHelper(IMongoCollection<BsonDocument> collection)   {    if (collection == null)    {     throw new ArgumentNullException("collection");    }    this.collection = collection;    this.bucket = new GridFSBucket(collection.Database);   }     public ObjectId UploadGridFSFromBytes(string filename, Byte[] source)   {    oid = bucket.UploadFromBytes(filename, source);    return oid;   }    public ObjectId UploadGridFSFromStream(string filename,Stream source)   {    using (source)    {     oid = bucket.UploadFromStream(filename, source);     return oid;    }   }    public Byte[] DownloadAsByteArray(ObjectId id)   {    Byte[] bytes = bucket.DownloadAsBytes(id);    return bytes;   }    public Stream DownloadToStream(ObjectId id)   {    Stream destination = new MemoryStream();    bucket.DownloadToStream(id, destination);    return destination;   }    public Byte[] DownloadAsBytesByName(string filename)   {    Byte[] bytes = bucket.DownloadAsBytesByName(filename);    return bytes;   }    public Stream DownloadToStreamByName(string filename)   {    Stream destination = new MemoryStream();    bucket.DownloadToStreamByName(filename, destination);    return destination;   }    public GridFSFileInfo FindFiles(string filename)   {    var filter = Builders<GridFSFileInfo>.Filter.And(    Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, "man"),    Builders<GridFSFileInfo>.Filter.Gte(x => x.UploadDateTime, new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc)),    Builders<GridFSFileInfo>.Filter.Lt(x => x.UploadDateTime, new DateTime(2017, 2, 1, 0, 0, 0, DateTimeKind.Utc)));    var sort = Builders<GridFSFileInfo>.Sort.Descending(x => x.UploadDateTime);    var options = new GridFSFindOptions    {     Limit = 1,     Sort = sort    };    using (var cursor = bucket.Find(filter, options))    {      fileInfo = cursor.ToList().FirstOrDefault();    }    return fileInfo;   }     public void DeleteAndRename(ObjectId id)   {    bucket.Delete(id);   }    //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.   public void DroppGridFSBucket()   {    bucket.Drop();   }    public void RenameAsingleFile(ObjectId id,string newFilename)   {    bucket.Rename(id, newFilename);   }    public void RenameAllRevisionsOfAfile(string oldFilename,string newFilename)   {    var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, oldFilename);    var filesCursor = bucket.Find(filter);    var files = filesCursor.ToList();    foreach (var file in files)    {     bucket.Rename(file.Id, newFilename);    }   }   } } 

ImageHelper.cs的代码如下:

using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks;  namespace MongoDemo {  public static class ImageHelper  {   /// <summary>   /// //将Image转换成流数据,并保存为byte[]    /// </summary>   /// <param name="image"></param>   /// <returns></returns>   public static byte[] ImageToBytes(Image image)   {    ImageFormat format = image.RawFormat;    using (MemoryStream ms = new MemoryStream())    {     if (format.Equals(ImageFormat.Jpeg))     {      image.Save(ms, ImageFormat.Jpeg);     }     else if (format.Equals(ImageFormat.Png))     {      image.Save(ms, ImageFormat.Png);     }     else if (format.Equals(ImageFormat.Bmp))     {      image.Save(ms, ImageFormat.Bmp);     }     else if (format.Equals(ImageFormat.Gif))     {      image.Save(ms, ImageFormat.Gif);     }     else if (format.Equals(ImageFormat.Icon))     {      image.Save(ms, ImageFormat.Icon);     }     byte[] buffer = new byte[ms.Length];     //Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin     ms.Seek(0, SeekOrigin.Begin);     ms.Read(buffer, 0, buffer.Length);     return buffer;    }   }     public static Stream ImageToStream(Image image)   {    ImageFormat format = image.RawFormat;    MemoryStream ms = new MemoryStream();     if (format.Equals(ImageFormat.Jpeg))    {     image.Save(ms, ImageFormat.Jpeg);    }    else if (format.Equals(ImageFormat.Png))    {     image.Save(ms, ImageFormat.Png);    }    else if (format.Equals(ImageFormat.Bmp))    {     image.Save(ms, ImageFormat.Bmp);    }    else if (format.Equals(ImageFormat.Gif))    {     image.Save(ms, ImageFormat.Gif);    }    else if (format.Equals(ImageFormat.Icon))    {     image.Save(ms, ImageFormat.Icon);    }    return ms;   }    //参数是图片的路径   public static byte[] GetPictureData(string imagePath)   {    FileStream fs = new FileStream(imagePath, FileMode.Open);    byte[] byteData = new byte[fs.Length];    fs.Read(byteData, 0, byteData.Length);    fs.Close();    return byteData;   }      /// <summary>   /// Convert Byte[] to Image   /// </summary>   /// <param name="buffer"></param>   /// <returns></returns>   public static Image BytesToImage(byte[] buffer)   {    MemoryStream ms = new MemoryStream(buffer);    Image image = System.Drawing.Image.FromStream(ms);    return image;   }    /// <summary>   /// Convert Byte[] to a picture and Store it in file   /// </summary>   /// <param name="fileName"></param>   /// <param name="buffer"></param>   /// <returns></returns>   public static string CreateImageFromBytes(string fileName, byte[] buffer)   {    string file = fileName;    Image image = BytesToImage(buffer);    ImageFormat format = image.RawFormat;    if (format.Equals(ImageFormat.Jpeg))    {     file += ".jpg";    }    else if (format.Equals(ImageFormat.Png))    {     file += ".png";    }    else if (format.Equals(ImageFormat.Bmp))    {     file += ".bmp";    }    else if (format.Equals(ImageFormat.Gif))    {     file += ".gif";    }    else if (format.Equals(ImageFormat.Icon))    {     file += ".icon";    }    System.IO.FileInfo info = new System.IO.FileInfo(Path.GetFullPath(@"DownLoadImg\")); //在当前程序集目录中添加指定目录DownLoadImg    System.IO.Directory.CreateDirectory(info.FullName);    File.WriteAllBytes(info+file, buffer);    return file;   }  } } 

LogHelper.cs代码如下:

/// <summary>  /// 手动记录错误日志,不用Log4Net组件  /// </summary>  public class LogHelper  {   /// <summary>   /// 将日志写入指定的文件   /// </summary>   /// <param name="Path">文件路径,如果没有该文件,刚创建</param>   /// <param name="content">日志内容</param>   public static void WriteFile(string content)   {    string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";    if (!Directory.Exists(Path))    {     //若文件目录不存在 则创建     Directory.CreateDirectory(Path);    }    Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";    if (!File.Exists(Path))    {     File.Create(Path).Close();    }    StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));    writer.WriteLine("时间:" + DateTime.Now.ToString());    writer.WriteLine("日志信息:" + content);    writer.WriteLine("-----------------------------------------------------------");    writer.Close();    writer.Dispose();   }    /// <summary>   /// 将日志写入指定的文件   /// </summary>   /// <param name="Path">文件路径,如果没有该文件,刚创建</param>   /// <param name="content">日志内容</param>   public static void WriteFile(int content)   {    string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";    if (!Directory.Exists(Path))    {     //若文件目录不存在 则创建     Directory.CreateDirectory(Path);    }    Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";    if (!File.Exists(Path))    {     File.Create(Path).Close();    }    StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));    writer.WriteLine("时间:" + DateTime.Now.ToString());    writer.WriteLine("日志信息:" + content);    writer.WriteLine("-----------------------------------------------------------");    writer.Close();    writer.Dispose();   }     /// <summary>   /// 将日志写入指定的文件   /// </summary>   /// <param name="erroMsg">错误详细信息</param>   /// <param name="source">源位置</param>   /// <param name="fileName">文件名</param>   public static void WriteFile(string erroMsg, string source, string stackTrace, string fileName)   {    string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";    if (!Directory.Exists(Path))    {     //若文件目录不存在 则创建     Directory.CreateDirectory(Path);    }    Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";    if (!File.Exists(Path))    {     File.Create(Path).Close();    }    StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));    writer.WriteLine("时间:" + DateTime.Now.ToString());    writer.WriteLine("文件:" + fileName);    writer.WriteLine("源:" + source);    writer.WriteLine("错误信息:" + erroMsg);    writer.WriteLine("-----------------------------------------------------------");    writer.Close();    writer.Dispose();   }  } 

结果如下:

Mongodb数据:

查找图片:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    MongoDB系列教程(五):mongo语法和mysql语法对比学习
    下一条:
    MongoDB在不同主机间复制数据库和集合的教程
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客