之前一篇文章介绍了如何在dos窗口下对MongoDB进行一些简单的操作,但是不管学习什么,最终还是要应用于自己的项目当中,本篇主要介绍在MVC框架中如何应用于我们的MongoDB。
GridFS介绍:@H_404_9@
GridFS是MongoDb中的一个内置功能,可以用于存放大量小文件。我们可以使用MongoVUE来辅助管理。
使用前提-MongoDB驱动安装:@H_404_9@
对于MongoDB驱动,目前主要有两种-官方驱动,samus驱动,我们再此使用官方驱动进行操作,下载地址:https://github.com/mongodb/mongo-csharp-driver/downloads
下载完成之后,进行解压缩包得到两个文件:
- MongoDB.Bson.dll 序列化,Json相关
- MongoDb.Driver.dll 驱动
将其加入到项目之中,添加引用,下边我们来看Demo实现:实现的效果就是一个简单的上传页面和上传view图片的界面。
利用GridFS上传图片:@H_404_9@
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,nFileLen);
//调用Write、WriteByte、WriteLine函数时需要手动设置上传时间
//通过Metadata 添加附加信息
MongoGridFSCreateOptions option = new MongoGridFSCreateOptions();
option.UploadDate = DateTime.Now;
//创建文件,文件并存储数据
using (MongoGridFSStream gfs = fs.Create(file.FileName,option))
{
gfs.Write(myData,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视图:@H_404_9@
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>
善于用工具来辅助管理自己的学习,提高效率。
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,nFileLen); //调用Write、WriteByte、WriteLine函数时需要手动设置上传时间 //通过Metadata 添加附加信息 MongoGridFSCreateOptions option = new MongoGridFSCreateOptions(); option.UploadDate = DateTime.Now; //创建文件,文件并存储数据 using (MongoGridFSStream gfs = fs.Create(file.FileName,option)) { gfs.Write(myData,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>界面显示+上传成功显示:
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>
善于用工具来辅助管理自己的学习,提高效率。