1. 程式人生 > >Mongodb學習筆記三、使用asp.net在Mongodb中儲存和讀取圖片檔案

Mongodb學習筆記三、使用asp.net在Mongodb中儲存和讀取圖片檔案

今天練習瞭如何使用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,可以用它看到存入的內容:


二、讀取

        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);
            }
        }
    }
}
當然,還有許多異常處理,命名規範等等,這裡就偷懶不處理了。週末放學回家咯,哈哈 ^ _ ^ 。