- Create table in SQL Server
- Integrate EntityFramework
- Create Controller and View
- Enable Async File upload in Razor View
- Save uploaded file into database
- Parameter with Async file upload
- Summary
Create Table in SQL Server
To create a new table in SQL, excute the below query.
- CREATE TABLE [dbo].[FileUpload](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [Filename] [nvarchar](100) NULL,
- [FileContent] [varbinary](max) NULL,
- [CreatedOn] [datetime] NULL,
- CONSTRAINT [PK_FileUpload] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
- 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.
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.common.min.css" />
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.silver.min.css" />
- <link rel="stylesheet" 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>
Add Upload Control
- <div class="demo-section k-content ">
- <div> <input name="AsyncDocumentsFiles" id="AsyncDocumentsId" type="file" accept="doc,pdf" /> </div>
- </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.
- <script type="text/javascript">
- $(document).ready(function() {
-
- $("#AsyncDocumentsId").kendoUpload({});
-
- $("#AsyncDocumentsId").closest(".k-upload").find("span").text("+ Add Files");
- });
- </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.
- namespace AsyncFileUpload {
- public class RouteConfig {
- public static void RegisterRoutes(RouteCollection routes) {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new {
- controller = "FileUpload", action = "Index", id = UrlParameter.Optional
- });
- }
- }
- }
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.
- $("#AsyncDocumentsId").kendoUpload({
- async: {
- saveUrl: "/FileUpload/Save",
- autoUpload: true
- },
- });
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.
- public ActionResult Save(IEnumerable < HttpPostedFileBase > AsyncDocumentsFiles) {
- if (AsyncDocumentsFiles != null) {
- CSharpcornerEntities dbcotext = new CSharpcornerEntities();
- foreach(var file in AsyncDocumentsFiles) {
- FileStream fs = new FileStream(file.FileName, FileMode.Open, FileAccess.Read);
- BinaryReader br = new BinaryReader(fs);
- Byte[] bytes = br.ReadBytes((Int32) fs.Length);
- var fileUpload = new FileUpload() {
- CreatedOn = DateTime.Now,
- Filename = file.FileName,
- FileContent = bytes
- };
- br.Close();
- fs.Close();
- dbcotext.FileUploads.Add(fileUpload);
- }
- }
-
- return Content("");
- }
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.
- <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.
- $("#AsyncDocumentsId").kendoUpload({
- async: {
- saveUrl: "/FileUpload/Save",
- autoUpload: true
- },
- upload: onUpload
- });
-
- function onUpload(e) {
- var keyInput = $("#keyInput").val();
- alert(keyInput);
- if (keyInput != null) {
- e.data = {
- KeyValue: keyInput
- };
- }
- }
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.
- 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 -
- @ {
- ViewBag.Title = "Index";
- } < link rel = "stylesheet"
- href = "http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.common.min.css" / > < link rel = "stylesheet"
- href = "http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.silver.min.css" / > < link rel = "stylesheet"
- 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() {
-
- $("#AsyncDocumentsId").kendoUpload({
- async: {
- saveUrl: "/FileUpload/Save",
- autoUpload: true
- },
- upload: onUpload
- });
-
- function onUpload(e) {
- var keyInput = $("#keyInput").val();
- if (keyInput != null) {
- e.data = {
- KeyValue: keyInput
- };
- }
- }
-
- $("#AsyncDocumentsId").closest(".k-upload").find("span").text("+ Add Files");
- }); < /script> < h2 > Kendo UI Async File Upload < /h2> < div > < div > Enter Key For File: < input type = "text"
- id = "keyInput" / > < /div> < br / > < br / > < div class = "demo-section k-content " > < div > < input name = "AsyncDocumentsFiles"
- id = "AsyncDocumentsId"
- type = "file"
- accept = "doc,pdf" / > < /div> < /div> < /div>
And, the Controller(FileUploadController.cs) will be -
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace AsyncFileUpload.Controllers {
- public class FileUploadController: Controller {
-
- public ActionResult Index() {
- return View();
- }
- public ActionResult Save(IEnumerable < HttpPostedFileBase > AsyncDocumentsFiles, string KeyValue) {
- if (AsyncDocumentsFiles != null) {
- using(CSharpcornerEntities cotext = new CSharpcornerEntities()) {
- foreach(var file in AsyncDocumentsFiles) {
- FileStream fs = new FileStream(file.FileName, FileMode.Open, FileAccess.Read);
- BinaryReader br = new BinaryReader(fs);
- Byte[] bytes = br.ReadBytes((Int32) fs.Length);
- var fileUpload = new FileUpload() {
- CreatedOn = DateTime.Now,
- Filename = file.FileName,
- FileContent = bytes
- };
- br.Close();
- fs.Close();
- cotext.FileUploads.Add(fileUpload);
- cotext.SaveChanges();
- }
- }
- }
-
- return Content("");
- }
- }
- }
- if ('this_is' == /an_example/) {
- of_beautifier();
- } else {
- var a = b ? (c % d) : e[f];
- }
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
- EntityFramework needs to be installed and configured
- Kendo UI must be reffered
- 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.