MongoDB 使用GridFS保存文件

      上篇文章说了一下怎么试用MongoDB来做replication,但是我是通过BSON Object来保存文件,这有个局限,就是如果文件超过4m就会抛出超过最大文件的异常。

根据官网介绍,BSON objects in MongoDB are limited to 4MB in size.   http://www.mongodb.org/display/DOCS/GridFS

 

因此重新写了那个操作类,使用GridFS来保存文件,代码很简单,但开始接触弄了比较长时间,有一个问题一直解决不了,我希望自己生成一个Guid的 _id 而不是mongodb生成的_id,但是一直解决不了,希望哪个高手看到指点一下,谢谢!

 

这个是使用Mongodb官网提供的客户端写的:

 

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Bson;
using MongoDB.Driver.GridFS;

namespace FileUtility
{
    public class DocUtility
    {
        private string connStr = "";
        public string ConnStr
        {
            get 
            {
                if (string.IsNullOrEmpty(connStr))
                {
                    throw new ArgumentNullException("Connection string did not specify!");
                }
                return connStr;
            }
        }
        public DocUtility()
        {
            connStr = System.Configuration.ConfigurationManager.AppSettings["FileDb"];
        }

        public DocUtility(string connectionString)
        {
            this.connStr = connectionString;
        }

        /// <summary>
        /// add a document to mongodb
        /// </summary>
        /// <param name="content">document bytes array</param>
        /// <returns>the unique identity filename in mongodb</returns>
        public string AddDoc(byte[] content)
        {
            MongoServer server = MongoServer.Create(this.ConnStr);
            try
            {
                string filename = Guid.NewGuid().ToString();
                server.Connect();
                MongoDatabase db = server.GetDatabase("ecDocs");
                MongoGridFS fs = new MongoGridFS(db, new MongoGridFSSettings() { Root="ecDocs" });
                MongoGridFSFileInfo info = new MongoGridFSFileInfo(fs, filename);
                using (MongoGridFSStream gfs = info.Create())
                {
                    gfs.Write(content, 0, content.Length);
                }
                return filename;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (server != null)
                    server.Disconnect();
            }
        }

        /// <summary>
        /// delete doc from mongodb
        /// </summary>
        /// <param name="filename">the unique identity filename</param>
        public string DeleteDoc(string filename)
        {
            MongoServer server = MongoServer.Create(this.ConnStr);
            try
            {
                server.Connect();
                MongoDatabase db = server.GetDatabase("ecDocs");
                MongoGridFS fs = new MongoGridFS(db, new MongoGridFSSettings() { Root = "ecDocs" });
                fs.Delete(filename);
                return filename;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (server != null)
                    server.Disconnect();
            }
        }

        /// <summary>
        /// get document bytes array from mongodb
        /// </summary>
        /// <param name="filename">unique filename</param>
        /// <returns>bytes array</returns>
        public byte[] GetDoc(string filename)
        {
            MongoServer server = MongoServer.Create(this.ConnStr);
            try
            {
                server.Connect();
                MongoDatabase db = server.GetDatabase("ecDocs");
                MongoGridFS fs = new MongoGridFS(db,new MongoGridFSSettings() { Root="ecDocs" });
                byte[] bytes = null;
                using (MongoGridFSStream gfs = fs.Open(filename, FileMode.Open))
                {
                    bytes = new byte[gfs.Length];
                    gfs.Read(bytes, 0, bytes.Length);
                }
                return bytes;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (server != null)
                    server.Disconnect();
            }
        }
    }
}

 

下面这个类是使用Samus的客户端:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB;
using MongoDB.GridFS;

namespace FileUtilitySamus
{
    public class DocUtility
    {
        private string connStr = "";
        public string ConnStr
        {
            get
            {
                if (string.IsNullOrEmpty(connStr))
                {
                    throw new ArgumentNullException("Connection string did not specify!");
                }
                return connStr;
            }
        }
        public DocUtility()
        {
            connStr = System.Configuration.ConfigurationManager.AppSettings["FileDb"];
        }

        public DocUtility(string connectionString)
        {
            this.connStr = connectionString;
        }

        /// <summary>
        /// add a document to mongodb
        /// </summary>
        /// <param name="content">document bytes array</param>
        /// <returns>the unique identity filename in mongodb</returns>
        public string AddDoc(byte[] content)
        {
            using (Mongo mongo = new Mongo(this.ConnStr))
            {
                try
                {
                    string filename = Guid.NewGuid().ToString();

                    mongo.Connect();
                    IMongoDatabase db = mongo.GetDatabase("ecDoc");

                    GridFile fs = new GridFile(db, "ecDoc");
                    GridFileInfo info = new GridFileInfo(db, "ecDoc", filename);
                    using (GridFileStream gfs = info.Create())
                    {
                        gfs.Write(content, 0, content.Length);
                    }

                    return filename;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        /// <summary>
        /// delete doc from mongodb
        /// </summary>
        /// <param name="filename">the unique identity filename</param>
        public void DeleteDoc(string filename)
        {
            using (Mongo mongo = new Mongo(this.ConnStr))
            {
                try
                {
                    mongo.Connect();
                    IMongoDatabase db = mongo.GetDatabase("ecDoc");

                    GridFile fs = new GridFile(db, "ecDoc");

                    fs.Delete(new Document("filename", filename));
                    
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        /// <summary>
        /// get document bytes array from mongodb
        /// </summary>
        /// <param name="filename">unique filename</param>
        /// <returns>bytes array</returns>
        public byte[] GetDoc(string filename)
        {
            using (Mongo mongo = new Mongo(this.ConnStr))
            {
                try
                {
                    mongo.Connect();
                    IMongoDatabase db = mongo.GetDatabase("ecDoc");
                    GridFile fs = new GridFile(db, "ecDoc");
                    GridFileStream gfs = fs.OpenRead(filename);
                    byte[] bytes = new byte[gfs.Length];
                    gfs.Read(bytes, 0, bytes.Length);
                    return bytes;
                }
                catch (Exception ex)
                {
                    if (ex.GetType() == typeof(System.IO.DirectoryNotFoundException))
                        throw new System.IO.FileNotFoundException("File not found :" + filename);
                    else
                        throw ex;
                }
            }
        }
    }
}

不知道两个客户端的性能相比如何?希望测试过的同学分享一下。

posted @ 2011-01-20 23:07  Chris Cheung  阅读(9269)  评论(2编辑  收藏  举报