標籤:
在做項目的時候我們遇到了視頻上傳的問題。正式開始項目之前做了一個簡單的Demo實現在MVC中視頻檔案的上
傳,考慮到將視頻放到MongoDB中上傳和讀取速度慢的問題,這次我們實現的檔案上傳是儲存的路徑,讀取的額時候
直接通過路徑讀取就OK了。 MVC,M指Model,我目前把它理解成三層中的Entity層,進行資料的傳遞,當然裡邊也可以放一些商務邏輯的代
碼。V,指View層,視圖,用於顯示介面,C指Controller,用於控制介面的顯示。MongoDB是現在非常流行的NoSQL數
據庫,具體的介紹前面有幾篇部落格已經介紹過了,大家可以看一下。 下面看一下代碼實現。 Mongo串連資料庫,跟我們以前串連資料庫的方法一樣,如下:
[csharp] view plaincopy
-
[csharp] view plaincopy
- public class DBcon
- {
- public const string _connectionString = "Server=192.168.24.***:27017";
-
- public const string _vediotest = "Vediotest";
- }
192.168.24.***是要已連線的服務器的網址,27017是伺服器指定的串連連接埠。本機地址,直接寫連接埠就可以。
接下來是實現向Mongo中添加資料的方法。
[csharp] view plaincopy
- //上傳視頻
- public static void AddVedio(VedioTestModels model)
- {
- using (Mongo mg = new Mongo(DBcon._connectionString))
- {
- mg.Connect();
- var db = mg.GetDatabase(DBcon._vediotest);
- var list = db.GetCollection<VedioTestModels>();
- list.Insert(model);
- }
- }
controler中的方法。
[csharp] view plaincopy
- //向資料庫中存入資訊
- [AcceptVerbs(HttpVerbs.Post)]
- public ActionResult Index2(HttpPostedFileBase file, HttpPostedFileBase text,VedioTestModels model)
- {
- if (file.ContentLength > 0)
- {
- //獲得儲存路徑
- string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
- Path.GetFileName(file.FileName));
- file.SaveAs(filePath);
-
- model.vedio = filePath;
- model.Id = Guid.NewGuid();
- model.vedioName = "../../Uploads/" + Path.GetFileName(file.FileName);
- //model.Id=Request["text"];
- Biz.BizModel.AddVedio(model);
- }
- return View();
- }
view中是以提交表單的方式實現的,向Controler中傳遞資料。
[csharp] view plaincopy
- @using (Html.BeginForm("Index2", "VedioTest", FormMethod.Post, new { enctype = "multipart/form-data" }))
- {
- @*<form action="upload" method="post" enctype="multipart/form-data"> *@
- <form>
- <input type="file" name="file" /><br />
- <input type="text" name="text" /><br />
- <input type="submit" name="Submit" id="Submit"/>
- </form>
- }
當然在串連mongo之前要開啟服務,首先開機mongo,其次開啟連接埠。這個可以通過寫批次檔,單擊批處理文
件開啟。
開啟mongo的代碼:mongod --dbpath E:\MongeDBData
開啟連接埠的代碼:mongo 127.0.0.1:27017/admin
下面展示一下實現的效果:
(1)選擇要上傳的檔案
(2)查詢資料庫,資料庫中已經加入上傳資訊
(3)檔案已經上傳到指定檔案加下(Uploads)
項目總結——MVC+MongoDB實現檔案上傳