NoSql-MongoDB GridFS + ASP. net mvc implements upload and display,

Source: Internet
Author: User
Tags mongodb driver

NoSql-MongoDB GridFS + ASP. net mvc implements upload and display,

The previous article introduced how to perform some simple operations on MongoDB in the dos window. However, no matter what you learn, you still need to apply it to your project, this article mainly introduces how to apply the MVC Framework to our MongoDB.

GridFS introduction:

GridFS is a built-in function in MongoDb that can be used to store a large number of small files. We can use the dedicated vue for management.

Prerequisites-MongoDB driver installation:

For MongoDB drivers, there are currently two main types-the official driver, samus driver, we then use the official driver for operations,: https://github.com/mongodb/mongo-csharp-driver/downloads

After the download is complete, extract the package to get two files:

  • MongoDB. Bson. dll serialization, Json-related
  • MongoDb. Driver. dll Driver

Add it to the project and add references. Let's look at the Demo Implementation below: The implementation is a simple page upload and view image upload interface.

Use GridFS to upload images: MongoDBHelper (Controller): connect to the database and upload Methods
Namespace MongoDBTest. controllers {public class MongoDBHelperController: Controller {private static MongoDatabase DB; public static string fileTable = "files "; /// <summary> /// set the connection to the database /// </summary> public void init () {// connect to the configuration file using the deleetmetadata method, flexible control of MongoDb database location string ConnectionString = ConfigurationManager. appSettings ["mondoDbConnection"]; // connect to the local database // string ConnectionString = "127.0.0.1 ";// If (String. isNullOrEmpty (ConnectionString) {throw new ArgumentNullException ("Connection string not found");} // create a Connection pool using serversettings using setting = new using serversettings (); Using setting. maxConnectionPoolSize = 15000; // you can specify the maximum number of connections in the connection pool. waitQueueSize = 500; // set the number of waiting queues. server = new MongoServerAddress (ConnectionString, 27017); int count = MongoServer. maxServerCount; Mo NgoServer server = Login server. create (export setting); // Create a connection data file DB = server. getDatabase ("DB3"); // create a database connection, connection string name} public void ProcessRequest () {init (); // pass the value from MVC, obtain string action = Request. queryString ["actions"]; // you can use the action value to determine whether to upload, retrieve, or DOWNLOAD switch (action) {case "DOWNLOAD": DownFile (); break; // download file case "UPLOAD": Upload (); break; // Upload File }}// UPLOAD File public void Upload () {try {HttpPostedFileBas E file = (HttpPostedFileBase) Request. files ["file"]; // get the length of the uploaded file int nFileLen = file. contentLength; // obtain the value of the uploaded file string nFileName = file. fileName; // create a gridfssetaskfssetting = new using gridfssettings () {Root = fileTable}; using GridFS fs = new using GridFS (DB, fsSetting ); byte [] myData = new Byte [nFileLen]; file. inputStream. read (myData, 0, nFileLen); // required to call the Write, WriteByte, and WriteLine Functions You need to manually set the upload time // Add the additional information through Metadata. Required gridfscreateoptions option = new required gridfscreateoptions (); option. uploadDate = DateTime. now; // create a file and store the data using (using gridfsstream gfs = fs. create (file. fileName, option) {gfs. write (myData, 0, nFileLen); gfs. close (); Response. write ("congratulations" + nFileName + "File Uploaded successfully! ") ;}} Catch (Exception e) {Response. Write (" Sorry your file is not upload successfully! "+ E. Message);} Response. End ();}
/// <Summary> /// Method for downloading files /// </summary> public void DownFile () {// obtain the file value string filename = Request. queryString ["value"]; // obtain the file type Response. contentType = "application/octet-stream"; // download + file name Response. addHeader ("Content-Disposition", "attachment; filename =" + filename); // obtain the image name ~gridfsset=fssetting = new ~gridfsset=() {Root = fileTable }; // query the value of gridfs fs = new distinct gridfs (DB, fsSetting) through the file name; distinct gridfsfileinfo gfInfo = new distinct gridfsfileinfo (fs, filename); // method 1, very concise fs. download (Response. outputStream, filename); Response. end ();}}}
MongoDbTest (View): upload interface display
<Html> <body> <div> @ * Find ProcessRequest and obtain the Action value to perform the operation * @ 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/> <input type =" submit "value =" Upload "style =" font-size: 20px "/>}</div> </body> Interface display + upload successful display:


Read images and audios from MongoDb and display them to View: MongoDBTest (Controller): assign values and search criteria
/// <Summary> /// click the student ID to splice the image name and display it on the page.-Hoya Jing-02:37:39, January 1, September 12, 2015 /// </summary> /// <returns> </returns> public ActionResult ImgTest () {// initialize string strPhotoUser = ""; // set false data and splice the image name strPhotoUser + = 130131199203216646 + ". jpg "; string strVoice =" "; strVoice ++ = 123 + ". mp3 "; // assign a value to ViewData. Assign ViewData [" img "] ="/MongoDBHelper/ProcessRequest to the ProcessRequest method under MongoDBHelper? Actions = DOWNLOAD & value = "+ strPhotoUser; // assign a value to ViewDate, and assign a value to the ProcessRequest method under MongoDBHelper ViewData [" voice "] ="/MongoDBHelper/ProcessRequest? Actions = DOWNLOAD & value = "+ strVoice; return View ();}
Note: In this case, only a fake data is assigned, and the idea is the same. You can obtain the image or audio name by splicing it and search for and display it in MongoDb. ImgTest (View ):
<Html> <body> <div> @ * obtain the ViewData value using the img attribute * @  </div> <div> @ * <p> <a href = ".. /.. /123.mp3 "> click </a> </p> * @ * The page appears. The loop attribute of automatic playback is loop playback. Therefore, this parameter is omitted * @ * using audio, the HTML plugin obtains ViewData audio * @ <audio src = "@ ViewData [" voice "]" preload = "auto" controls autoplay> <div class = "audioplayer-playing"> </div> </audio> </div> </body> We assign two ViewData values, image + audio values, and finally display the view effect:

In this way, we can achieve the desired effect. For MongoDB, we can use the MongoVUE software to help manage the images and audios we uploaded:

Good at using tools to help you manage your learning and improve efficiency.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.