数据库

 首页 > 数据库 > MongoDB > MongoDB如何使用GridFS方式保存文件

MongoDB如何使用GridFS方式保存文件

分享到:
【字体:
导读:
         摘要:根据官网介绍,BSONobjectsinMongoDBarelimitedto4MBinsize.http://www.mongodb.org/display/DOCS/GridFS因此重新写了那个操作类,使用GridFS来保存文件,代码很简单,但开始接触弄了比较长时间,有一个问题一直解决不了,我希望自己生成一个Gui...

MongoDB如何使用GridFS方式保存文件

根据官网介绍,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;
        }

        /// 
        /// add a document to mongodb
        /// 

        /// document bytes array
        /// the unique identity filename in mongodb
        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();
            }
        }

        /// 
        /// delete doc from mongodb
        /// 

        /// the unique identity filename
        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();
            }
        }

        /// 
        /// get document bytes array from mongodb
        /// 

        /// unique filename
        /// bytes array
        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;
        }

        /// 
        /// add a document to mongodb
        /// 

        /// document bytes array
        /// the unique identity filename in mongodb
        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;
                }
            }
        }

        /// 
        /// delete doc from mongodb
        /// 

        /// the unique identity filename
        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;
                }
            }
        }

        /// 
        /// get document bytes array from mongodb
        /// 

        /// unique filename
        /// bytes array
        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;
                }
            }
        }
    }
}


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

MongoDB如何使用GridFS方式保存文件
分享到:
MongoDB与GridFS文件系统
MongoDB与GridFS文件系统 GridFS用于存储和恢复那些超过16M(BSON文件限制)的文件。 GridFS将文件分成大块,将每个大块存储为单独的文件.GridFS中限制chunk最大为256k。GridFS使用两个collection存储,一个存储chunks,一个存储元数据(metadata)。 fs.files和fs.chunks When should I use GridFS? http://docs.mon...
MongoDB和MySQL在使用上的区别
MongoDB和MySQL在使用上的区别 两个在不同领域发展非常不错的数据库,MongoDB(NoSQL)、MYSQL(关系型)记录下他们的区别,以及各自使用的环境。 MongoDB是牺牲空间来换来强扩展性and某一方面极大的速度提升。。 简单来说。 关系型数据库的关系+事务。mongodb为首的nosql没有 关系型数据库插入100w数据以mysql为例需要大概...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……