Asynchronous File Upload Using Kendo UI Async Upload With MVC And Entity Framework

Prerequisites
  • Basic knowledge in Kendo UI
  • Basic knowledge in MVC
  • Basic knowledge in Entity Framework
  • Basic knowledge In jQuery 
Article Flow 
  1. Create table in SQL Server
  2. Integrate EntityFramework
  3. Create Controller and View
  4. Enable Async File upload in Razor View 
  5. Save uploaded file into database
  6. Parameter with Async file upload
  7. Summary
Create Table in SQL Server

To create a new table in SQL, excute the below query.
  1. CREATE TABLE [dbo].[FileUpload](  
  2. [Id] [int] IDENTITY(1,1) NOT NULL,  
  3. [Filename] [nvarchar](100) NULL,  
  4. [FileContent] [varbinary](maxNULL,  
  5. [CreatedOn] [datetime] NULL,  
  6. CONSTRAINT [PK_FileUpload] PRIMARY KEY CLUSTERED  
  7. (  
  8. [Id] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  11. GO   
After excution, your table design will be like the image below.
 
 
Integrate EntityFramework

Before  moving to this step, create one empty project in MVC. Once the project is created, follow the below steps to integrate Entity Framework with your MVC application.
 
Step 1 (Install Entity Framwork from NuGet)

Right click on References under your project and select "Manage NuGet Packes" to install EF.
 
 
 
Click browse, search for EntityFrawork and click Install.
 
 
 
After this, you need to accept the licence terms.



Once you accept the license, the Entity Framework will refer to your resepective project. In the below image, you can see that the Entity Framework has been added in references.
 


Step 2 (Add ADO.NET Entity Data Model)

 
And give a name for Entity Model.

 

We already have the existing db, so we will move on to the Database first apporach model. To select the database first approach, select "EF Designer from database" and click Next 
 
 

To set a new connection, follow the steps mentioned in the below image.

 

After creating connection, create a connection string for your application. Then, check the "Save connection settings in web.config.cs" option and click Next.
 
 
 
Select the respective table to map your application and database.

 
 
Now, you can see, Enity Framework has been integrated with your application and database tables.
 
 
 
Now, you can see the configured connection in webconfig.cs file.
 
 
 
Create Controller and View
 
Creating Controller 
 
To create a Controller, right click on the Controllers folder under your project, and follow the below steps.
 
 

Select an empty Controller.

 

After clicking Add button, and giving proper name to the Controller, click "Add"  button again.

 
 
Creating View
 
To create a View, right click on respective action method and select Add View. Here, index method is default action method and I am using the same action method. 

 
 
Create a View without model.

 
 
Enable Async file upload in Razor View
 
Call Kendo Scripts and CSS 

To access predefined functionality from Kendo UI, we need to call the following scripts and css in our application. So, just add the below references in head tag.
  1. <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.common.min.css" />  
  2. <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.silver.min.css" />  
  3. <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.mobile.all.min.css" />  
  4. <script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>  
  5. <script src="http://kendo.cdn.telerik.com/2017.1.118/js/kendo.all.min.js"></script>  
Add Upload Control 
  1. <div class="demo-section k-content ">  
  2.     <div> <input name="AsyncDocumentsFiles" id="AsyncDocumentsId" type="file" accept="doc,pdf" /> </div>  
  3. </div>  
Enable Kendo async file upload controller to html5 file upload controller

To enable async file upload Controller to our HTML 5 file, add the kendoUpload() method to the respective control, like below.
  1. <script type="text/javascript">  
  2.     $(document).ready(function() {  
  3.         //Enable Kendo Uploader to Normal Uploader control  
  4.         $("#AsyncDocumentsId").kendoUpload({});  
  5.         //Adding Kendo Css  
  6.         $("#AsyncDocumentsId").closest(".k-upload").find("span").text("+ Add Files");  
  7.     });  
  8. </script>  
Run our application by changing routeconfig.cs

Now, run the application by changing the Controller name and action name in routeconfig.cs in your App_Start folder, under your project application.

 
  1. namespace AsyncFileUpload {  
  2.     public class RouteConfig {  
  3.         public static void RegisterRoutes(RouteCollection routes) {  
  4.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  5.             routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new {  
  6.                 controller = "FileUpload", action = "Index", id = UrlParameter.Optional  
  7.             });  
  8.         }  
  9.     }  
  10. }  
Now, you can see the input control enabled with Kendo Async file upload control.

 

Save uploaded file into database

To perform "Save" operation, we need to enable the async save url from kendoupload control as below.
  1. $("#AsyncDocumentsId").kendoUpload({  
  2.     async: {  
  3.         saveUrl: "/FileUpload/Save",  
  4.         autoUpload: true  
  5.     },  
  6. });  
Here, the saveUrl represents same domain fileupload control and action method save; AutoUpload true represents that it instantly saves the file while uploading. I have added the "Save" action method in fileupload Controller as below.
  1. public ActionResult Save(IEnumerable < HttpPostedFileBase > AsyncDocumentsFiles) {  
  2.     if (AsyncDocumentsFiles != null) {  
  3.         CSharpcornerEntities dbcotext = new CSharpcornerEntities();  
  4.         foreach(var file in AsyncDocumentsFiles) {  
  5.             FileStream fs = new FileStream(file.FileName, FileMode.Open, FileAccess.Read);  
  6.             BinaryReader br = new BinaryReader(fs);  
  7.             Byte[] bytes = br.ReadBytes((Int32) fs.Length);  
  8.             var fileUpload = new FileUpload() {  
  9.                 CreatedOn = DateTime.Now,  
  10.                     Filename = file.FileName,  
  11.                     FileContent = bytes  
  12.             };  
  13.             br.Close();  
  14.             fs.Close();  
  15.             dbcotext.FileUploads.Add(fileUpload);  
  16.         }  
  17.     }  
  18.     // Return an empty string to signify success  
  19.     return Content("");  
  20. }  
Explanation for the above Save method

CSharpcornerEntities -> EntityFramework Context Name

dbcotext.FileUploads.Add(fileUpload)-> Inserting fileUpload object value to FileUploads Table

dbcotext.SaveChanges();->Now we perform the save/update operation to existing or new value to respective table or full database
 
Now, run your application.
 
Upload File(s)

 
Save to DB
 
Here, you can see that we have received the uploaded files in action method.
 
 
 
Data Saved in DB 
 
Now, check and see the database table. The value has been inserted in the below mentioned table.
 


After successfull insertion of upload, you can see your screen like below.

 

Parameter with Async File upload

Sometimes, we are in the position to parameter while uploading file. Just assume our client is asking us to pass some key to each files and that key should concatenated with filename. Let's add one textbox in View to pass the textbox value to Controller.
  1. <div> Enter Key For File:<input type="text" id="keyInput" /></div>  
We need to pass this textbox value while uploading the document. So now, I am going to enable the upload event in kendouploader.
  1. $("#AsyncDocumentsId").kendoUpload({  
  2.     async: {  
  3.         saveUrl: "/FileUpload/Save",  
  4.         autoUpload: true  
  5.     },  
  6.     upload: onUpload  
  7. });  
  8.   
  9. function onUpload(e) {  
  10.     var keyInput = $("#keyInput").val();  
  11.     alert(keyInput);  
  12.     if (keyInput != null) {  
  13.         e.data = {  
  14.             KeyValue: keyInput  
  15.         };  
  16.     }  
  17. }  
For clearer picture, refer the below image.
 
 

Now, let's run our application and enter the KeyInput. But before that, add parameter to Save action method as below.
  1. public ActionResult Save(IEnumerable<HttpPostedFileBase> AsyncDocumentsFiles,string KeyValue)   
Passing keyinput and files while uploading

 
  
Getting Parameter and files 

In the below screen, we can see the uploaded files with value for parameter. 

 

Finally the View (index.cshtml) will be -
  1. @ {  
  2.     ViewBag.Title = "Index";  
  3. } < link rel = "stylesheet"  
  4. href = "http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.common.min.css" / > < link rel = "stylesheet"  
  5. href = "http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.silver.min.css" / > < link rel = "stylesheet"  
  6. href = "http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.mobile.all.min.css" / > < script src = "http://code.jquery.com/jquery-1.12.4.min.js" > < /script> < script src = "http://kendo.cdn.telerik.com/2017.1.118/js/kendo.all.min.js" > < /script> < script type = "text/javascript" > $(document).ready(function() {  
  7.     //Enable Kendo Uploader to Normal Uploader control  
  8.     $("#AsyncDocumentsId").kendoUpload({  
  9.         async: {  
  10.             saveUrl: "/FileUpload/Save",  
  11.             autoUpload: true  
  12.         },  
  13.         upload: onUpload  
  14.     });  
  15.   
  16.     function onUpload(e) {  
  17.         var keyInput = $("#keyInput").val();  
  18.         if (keyInput != null) {  
  19.             e.data = {  
  20.                 KeyValue: keyInput  
  21.             };  
  22.         }  
  23.     }  
  24.     //Adding Kendo Css  
  25.     $("#AsyncDocumentsId").closest(".k-upload").find("span").text("+ Add Files");  
  26. }); < /script> < h2 > Kendo UI Async File Upload < /h2> < div > < div > Enter Key For File: < input type = "text"  
  27. id = "keyInput" / > < /div> < br / > < br / > < div class = "demo-section k-content " > < div > < input name = "AsyncDocumentsFiles"  
  28. id = "AsyncDocumentsId"  
  29. type = "file"  
  30. accept = "doc,pdf" / > < /div> < /div> < /div>  
And, the Controller(FileUploadController.cs) will be -
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. namespace AsyncFileUpload.Controllers {  
  8.     public class FileUploadController: Controller {  
  9.         // GET: FileUpload  
  10.         public ActionResult Index() {  
  11.             return View();  
  12.         }  
  13.         public ActionResult Save(IEnumerable < HttpPostedFileBase > AsyncDocumentsFiles, string KeyValue) {  
  14.             if (AsyncDocumentsFiles != null) {  
  15.                 using(CSharpcornerEntities cotext = new CSharpcornerEntities()) {  
  16.                     foreach(var file in AsyncDocumentsFiles) {  
  17.                         FileStream fs = new FileStream(file.FileName, FileMode.Open, FileAccess.Read);  
  18.                         BinaryReader br = new BinaryReader(fs);  
  19.                         Byte[] bytes = br.ReadBytes((Int32) fs.Length);  
  20.                         var fileUpload = new FileUpload() {  
  21.                             CreatedOn = DateTime.Now,  
  22.                                 Filename = file.FileName,  
  23.                                 FileContent = bytes  
  24.                         };  
  25.                         br.Close();  
  26.                         fs.Close();  
  27.                         cotext.FileUploads.Add(fileUpload);  
  28.                         cotext.SaveChanges();  
  29.                     }  
  30.                 }  
  31.             }  
  32.             // Return an empty string to signify success  
  33.             return Content("");  
  34.         }  
  35.     }  
  36. // This is just a sample script. Paste your real code (javascript or HTML) here.  
  37. if ('this_is' == /an_example/) {  
  38.     of_beautifier();  
  39. else {  
  40.     var a = b ? (c % d) : e[f];  
  41. }   
Summary

In this article, we learned how to create database first approach in EntityFramework, enable keno UI async file upload, pass the parameter to async file upload while uploading documents, and how to insert the uploaded file into database
 
Note
  1. EntityFramework needs to be installed and configured
  2. Kendo UI must be reffered 
  3. Kendo UI must be configured with respective upload control  
For more configuration kendo async file upload refer this link http://docs.telerik.com/kendo-ui/api/javascript/ui/upload 
 
I have attached the view and controller only as source code
 
I hope it's helpful.


Similar Articles