今天练习了如何使用c# driver存储和读取图片。


废话不多说,直接上代码。

一、存储图片(文件应该也一样):

private void SaveImgBJSON(string id, byte[] byteImg)
        {
            BsonDocument doc = new BsonDocument();
            doc["ID"] = id;
            doc["Img"] = byteImg;

            //链接字符串
            var connectionString = "mongodb://localhost";

            //定义Mongo服务 
            var client = new MongoClient(connectionString);

            var server = client.GetServer();
            //获取databaseName对应的数据库,不存在则自动创建 
            var database = server.GetDatabase("test");

            //获取 "entities" 对应的集合,不存在则自动创建  
            var collection = database.GetCollection<BsonDocument>("imgTest");
            collection.Save(doc);
        }



传入ID和字节流就可以了。

在界面中拖一个BUTTON,然后在点击事件中将文件读入并调用上面的方法,就可以存入了。

protected void Button1_Click(object sender, EventArgs e)
        {
            FileInfo fi = new FileInfo(@"E:\myPic\123.jpg");
            long len = fi.Length;

            FileStream fs = new FileStream(@"E:\myPic\123.jpg", FileMode.Open);
            byte[] buf = new byte[len];

            fs.Read(buf, 0, (int)len);
            fs.Close();

            SaveImgBJSON("123", buf);
        }

发现一款图形化管理工具:Mongo-Cola,可以用它看到存入的内容:

mongodb 存储大量图片 mongodb保存图片_数据库


二、读取

public byte[] GetImgBJSON()
        {
            string connectionString = "mongodb://localhost";
            //定义Mongo服务 
            var client = new MongoClient(connectionString);

            var server = client.GetServer();
            //获取databaseName对应的数据库,不存在则自动创建 
            var database = server.GetDatabase("test");

            //获取 "entities" 对应的集合,不存在则自动创建  
            var collection = database.GetCollection<QueryDocument>("imgTest");

            BsonDocument doc = collection.FindOne(new QueryDocument { { "ID", "123" } });

            byte[] buf = (byte[])doc.GetValue("Img");

            return buf;
        }



接下来就是如何显示的问题了。

新建readMongodbPic.ashx页面,在ProcessRequest调用上面的读取函数就OK了。

public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/png";
            context.Response.BinaryWrite(GetImgBJSON());
        }



然后只要写一个<image src="readMongodbPic.ashx"/>这样的标签就可以了,将显示出刚刚存入的图片。

比如,新建BUTTON,然后在点击事件中写入以下代码:

protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Write("<image src='readMongodbPic.ashx'/>");
        }




至此,已经完成了简单的读写图片。

接下来改进一下,做一个简单的让用户选择上传图片,并保存功能:

拖入FileUpload控件和一个BUTTON,在BUTTON的点击事件中写入以下代码:

protected void Button3_Click(object sender, EventArgs e)
        {
            if (Request.Files.Count > 0)
            {
                HttpPostedFile imgFile = Request.Files[0];
                byte[] bytes = new byte[imgFile.ContentLength];
                BinaryReader reader = new BinaryReader(imgFile.InputStream, Encoding.UTF8);
                bytes = reader.ReadBytes(imgFile.ContentLength);
                string name = Request.Files[0].FileName;
                string id = name.Substring(0, name.IndexOf('.'));
                SaveImgBJSON(id, bytes);

                Response.Write("上传成功, id=" + id);
            }
        }



然后给读文件的部分也添加参数,以便于查找显示任意ID图片:

1、修改读mongodb函数:public byte[] GetImgBJSON(string id),和这里BsonDocument doc = collection.FindOne(new QueryDocument { { "ID", id

2、页面处理函数ProcessRequest中添加参数获取:NameValueCollection nvc = context.Request.Params; string id = nvc["id"];

3、相应的,显示图片那个BUTTON点击中的代码也要改变:Response.Write("<image src='readMongodbPic.ashx?id=123'/>"); ps:这里也可以再加个textbox由用户输入,这样就完美了。偷个懒不改了。

至此简单的读写就实现了。


最后,再对代码做一下整理:

新建一个Mongodb读写类readMongodbPic,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using MongoDB.Bson;
using MongoDB.Driver;
//using MongoDB.Driver.Builders;
//using MongoDB.Driver.GridFS;

namespace MongodbTest
{
    public class RWMongodbPic
    {
        //链接字符串
        const string connectionString = "mongodb://localhost";

        /// <summary>
        /// 获得保存图片的集合
        /// </summary>
        /// <returns></returns>
        private MongoCollection<QueryDocument> GetCollection()
        {
            //定义Mongo服务 
            var client = new MongoClient(connectionString);

            var server = client.GetServer();
            //获取databaseName对应的数据库,不存在则自动创建 
            var database = server.GetDatabase("test");

            //获取 "entities" 对应的集合,不存在则自动创建  
            return database.GetCollection<QueryDocument>("imgTest");
        }

        /// <summary>
        /// 根据ID读取内容
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>字节流</returns>
        public byte[] GetImgBJSON(string id)
        {
            var collection = GetCollection();
            BsonDocument doc = collection.FindOne(new QueryDocument { { "ID", id } });
            byte[] buf = (byte[])doc.GetValue("Img");

            return buf;
        }

        /// <summary>
        /// 保存字节流文件
        /// </summary>
        /// <param name="id">要存入的ID</param>
        /// <param name="byteImg">文件字节流</param>
        public void SaveImgBJSON(string id, byte[] byteImg)
        {
            BsonDocument doc = new BsonDocument();
            doc["ID"] = id;
            doc["Img"] = byteImg;

            var collection = GetCollection();
            collection.Save(doc);
        }
    }
}


readMongodbPic.ashx代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Collections.Specialized;

namespace MongodbTest
{
    /// <summary>
    /// readMongodbPic 的摘要说明
    /// </summary>
    public class readMongodbPic : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            NameValueCollection nvc = context.Request.Params;
            string id = nvc["id"];
            if (string.IsNullOrEmpty(id))
            {
                context.Response.Write("id不能为空!");
            }
            RWMongodbPic mop = new RWMongodbPic();
            context.Response.ContentType = "image/png";
            context.Response.BinaryWrite(mop.GetImgBJSON(id));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}



Default.aspx中的代码如下:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

using System.IO;


namespace MongodbTest
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            FileInfo fi = new FileInfo(@"E:\myPic\123.jpg");
            long len = fi.Length;

            FileStream fs = new FileStream(@"E:\myPic\123.jpg", FileMode.Open);
            byte[] buf = new byte[len];

            fs.Read(buf, 0, (int)len);
            fs.Close();

            RWMongodbPic mop = new RWMongodbPic();
            mop.SaveImgBJSON("123", buf);
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Write("<image src='readMongodbPic.ashx?id=123'/>");
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            if (Request.Files.Count > 0)
            {
                HttpPostedFile imgFile = Request.Files[0];
                byte[] bytes = new byte[imgFile.ContentLength];
                BinaryReader reader = new BinaryReader(imgFile.InputStream, Encoding.UTF8);
                bytes = reader.ReadBytes(imgFile.ContentLength);
                string name = Request.Files[0].FileName;
                string id = name.Substring(0, name.IndexOf('.'));

                RWMongodbPic mop = new RWMongodbPic();
                mop.SaveImgBJSON(id, bytes);

                Response.Write("上传成功, id=" + id);
            }
        }
    }
}

当然,还有许多异常处理,命名规范等等,这里就偷懒不处理了。周末放学回家咯,哈哈 ^ _ ^ 。