专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > NoSQL

NoSql-MongoDB GridFS+ASP.NET MVC实现上传,展示

发布时间:2010-05-20 14:01:29 文章来源:www.iduyao.cn 采编人员:星星草
NoSql-MongoDB GridFS+ASP.NET MVC实现上传,显示

     之前一篇文章介绍了如何在dos窗口下对MongoDB进行一些简单的操作,但是不管学习什么,最终还是要应用于自己的项目当中,本篇主要介绍在MVC框架中如何应用于我们的MongoDB。

GridFS介绍:

     GridFS是MongoDb中的一个内置功能,可以用于存放大量小文件。我们可以使用MongoVUE来辅助管理。

使用前提-MongoDB驱动安装:

     对于MongoDB驱动,目前主要有两种-官方驱动,samus驱动,我们再此使用官方驱动进行操作,下载地址:https://github.com/mongodb/mongo-csharp-driver/downloads

下载完成之后,进行解压缩包得到两个文件:

  • MongoDB.Bson.dll   序列化,Json相关
  • MongoDb.Driver.dll   驱动

     将其加入到项目之中,添加引用,下边我们来看Demo实现:实现的效果就是一个简单的上传页面和上传view图片的界面。

利用GridFS上传图片:

MongoDBHelper(Controller):连接数据库,上传方法

namespace MongoDBTest.Controllers
{
    public class MongoDBHelperController : Controller
    {
        private static MongoDatabase DB;
        public static string fileTable = "files";
        /// <summary>
        /// 连接数据库设置
        /// </summary>
        public void init()
        {
            //使用AppSettings方式和配置文件连接,灵活控制MongoDb数据库位置
            string ConnectionString = ConfigurationManager.AppSettings["mondoDbConnection"];
            //连接本地的数据库
            //string ConnectionString = "127.0.0.1";
            //连接不成功,提示
            if (String.IsNullOrEmpty(ConnectionString))
            {
                throw new ArgumentNullException("Connection string not found");
            }
            //创建连接池
            MongoServerSettings mongoSetting = new MongoServerSettings();
            mongoSetting.MaxConnectionPoolSize = 15000;//设定最大连接池
            mongoSetting.WaitQueueSize = 500;//设定等待队列数
            mongoSetting.Server = new MongoServerAddress(ConnectionString, 27017);
            int count = MongoServer.MaxServerCount;
            MongoServer server = MongoServer.Create(mongoSetting);//创建连接数据文件

            DB = server.GetDatabase("DB3");//创建数据库连接,连接的字符串名称
        }

        public void ProcessRequest()
        {
            init();
            //从MVC传值,获取
            string action = Request.QueryString["actions"];
            //通过action值来判断是上传,还是获取,还是下载等
            switch (action)
            {
                case "DOWNLOAD": DownFile(); break; //下载文件
                case "UPLOAD": Upload(); break; //上传文件
            }
        }

        //上传文件
        public void Upload()
        {
            try
            {
                HttpPostedFileBase file = (HttpPostedFileBase)Request.Files["file"];
                //获取上传文件的长度
                int nFileLen = file.ContentLength;
                //获取上传文件的值
                string nFileName = file.FileName;
                //利用GridFS 创建
                MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = fileTable };
                MongoGridFS fs = new MongoGridFS(DB, fsSetting);

                byte[] myData = new Byte[nFileLen];
                file.InputStream.Read(myData, 0, nFileLen);
                //调用Write、WriteByte、WriteLine函数时需要手动设置上传时间
                //通过Metadata 添加附加信息
                MongoGridFSCreateOptions option = new MongoGridFSCreateOptions();
                option.UploadDate = DateTime.Now;
                //创建文件,文件并存储数据
                using (MongoGridFSStream gfs = fs.Create(file.FileName, option))
                {
                    gfs.Write(myData, 0, nFileLen);
                    gfs.Close();
                    Response.Write("恭喜您" + nFileName + "文件上传成功!");
                }
            }
            catch (Exception e)
            {
                Response.Write("Sorry your file is not upload successfully!" + e.Message);
            }

            Response.End();
        }
        /// <summary>
        /// 下载文件方法
        /// </summary>
        public void DownFile()
        {
            //获取文件值
            string filename = Request.QueryString["value"];
            //获取文件类型
            Response.ContentType = "application/octet-stream";
            //实现下载+文件名
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
            //获取图片名
            MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = fileTable };
            //通过文件名去数据库查值
            MongoGridFS fs = new MongoGridFS(DB, fsSetting);
            MongoGridFSFileInfo gfInfo = new MongoGridFSFileInfo(fs, filename);
            //方法一,很简洁
            fs.Download(Response.OutputStream, filename);
            Response.End();
        }
    }
}

MongoDbTest(View):上传界面显示

<html>
<body>
    <div>
        @*找到ProcessRequest,通过获取Action值来执行操作*@
        @using (Html.BeginForm("ProcessRequest", "MongoDBHelper", new { actions = "UPLOAD" }, FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            <input type="file" name="file" id="file" style="font-size:20px;" />
            <br/>
            <br/>
            <input type="submit" value="上传" style="font-size:20px" />
        }
    </div>
</body>
</html>
界面显示+上传成功显示:


从MongoDb读取图片,音频,显示到View视图:

MongoDBTest(Controller):赋值,查找条件

        /// <summary>
        /// 通过学号拼接图片名称显示到界面-霍亚静-2015年9月12日02:37:39
        /// </summary>
        /// <returns></returns>
        public ActionResult ImgTest()
        {
            //初始化
            string strPhotoUser = "";
            //设置假数据,拼接图片名称
            strPhotoUser += 130131199203216646 + ".jpg";

            string strVoice = "";
            strVoice += 123 + ".mp3";
            //给ViewData赋值,给MongoDBHelper 下的ProcessRequest方法赋值
            ViewData["img"] = "/MongoDBHelper/ProcessRequest?actions=DOWNLOAD&value=" + strPhotoUser;
            //给ViewDate赋值,给MongoDBHelper 下的ProcessRequest方法赋值
            ViewData["voice"] = "/MongoDBHelper/ProcessRequest?actions=DOWNLOAD&value=" + strVoice;
            return View();
        }
     注:再此,只是赋了一个假数据,思想都一样,通过拼接的方式得到图片或者音频等的名称,去MongoDb查找,显示。

ImgTest(View):

<html>
<body>
    <div>
        @*利用img属性获取ViewData值*@
        <img src="@ViewData["img"]" style="width:auto;height:auto;" />
    </div>
    <div>
        @*<p><a href="../../123.mp3">点击</a></p>*@
        @*出现界面,自动播放 loop属性是循环播放的,所以在此省略*@
        @*利用audio,HTML插件获取ViewData音频*@
        <audio src="@ViewData["voice"]" preload="auto" controls autoplay >
            <div class="audioplayer audioplayer-playing"></div>
        </audio>
    </div>
</body>
</html>
我们赋值两个ViewData,图片+音频,最终显示到视图的效果:

     这样就达到我们想要的效果了。对于MongoDB,我们可以采用MongoVUE软件来辅助管理,看看我们上传的图片和音频:


     善于用工具来辅助管理自己的学习,提高效率。

版权声明:本文为博主原创文章,未经博主允许不得转载。

2楼u010924834昨天 23:54
总结得很认真,赞一个!
1楼u010924834昨天 23:54
总结得很认真,赞一个!
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: