Asynchronous File Uploading in Kendo UI Using WEB API

This article shows how to do asynchronous file uploading in KendoUI using the following ways:

            1)   Processing the multipart MIME data using Web API.

            2)   Using Generic Handler

Uploading file by processing the multipart MIME data

Here I will use the following:

  • Kendo Upload control with MVVM pattern
  • Web API 2

The first thing we need to do is create a Web API project as in the following figure:

   
                                                                                             
    
 
Create an HTML page in the project. In my case I named it AyncUpload.html.

Write the following code.

AyncUpload.html

  1. <head>  
  2.     <title>Kendo Upload</title>  
  3.     <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.common.min.css">  
  4.         <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.default.min.css">  
  5.             <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.dataviz.min.css">  
  6.                 <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.dataviz.default.min.css">  
  7.                     <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>  
  8.                     <script src="http://cdn.kendostatic.com/2015.1.408/js/kendo.all.min.js"></script>  
  9.                 </head>  
  10.                 <body>  
  11.                     <div id="example">  
  12.                         <div class="demo-section k-header">  
  13.                             <div>  
  14.                                 <h4>Upload files</h4>  
  15.                                 <input name="files"  
  16.   
  17. type="file"  
  18.   
  19. data-role="upload"  
  20.   
  21. data-async="{ saveUrl: ‘api/Upload',autoUpload: true }"  
  22.   
  23. data-bind="visible: isVisible,enabled: isEnabled">  
  24.                                 </div>  
  25.                             </div>  
  26.                         </div>  
  27.                     </body>  
  28.                 </html>  

JavaScript

  1. $(document).ready(function() {  
  2.   
  3.     var viewModel = kendo.observable({  
  4.   
  5.         isEnabled: true,  
  6.   
  7.         isVisible: true,  
  8.   
  9.     });  
  10.   
  11.     kendo.bind($("#example"), viewModel);  
  12.   
  13. });  
Right-click on the controller folder, select Add, then click Controller. Create a Web API 2 controller as in the following figure:
 
    
 
   
 
In my case I named it UploadController.cs.

Write the following code in the UploadController class.

  1. public async Task < HttpResponseMessage > PostFile()  
  2.   
  3. {  
  4.   
  5.   
  6.     if (!Request.Content.IsMimeMultipartContent())  
  7.   
  8.     {  
  9.   
  10.         throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);  
  11.   
  12.     }  
  13.   
  14.     string root = HttpContext.Current.Server.MapPath("~/App_Data");  
  15.   
  16.     var provider = new MultipartFormDataStreamProvider(root);  
  17.   
  18.     try  
  19.   
  20.     {  
  21.   
  22.         StringBuilder sb = new StringBuilder();  
  23.   
  24.   
  25.         await Request.Content.ReadAsMultipartAsync(provider);  
  26.   
  27.   
  28.         foreach(var key in provider.FormData.AllKeys)  
  29.   
  30.         {  
  31.   
  32.             foreach(var val in provider.FormData.GetValues(key))  
  33.   
  34.             {  
  35.   
  36.                 sb.Append(string.Format("{0}: {1}\n", key, val));  
  37.   
  38.             }  
  39.   
  40.         }  
  41.   
  42.   
  43.         foreach(var file in provider.FileData)  
  44.   
  45.         {  
  46.   
  47.             FileInfo fileInfo = new FileInfo(file.LocalFileName);  
  48.   
  49.             sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length));  
  50.   
  51.         }  
  52.   
  53.         return new HttpResponseMessage()  
  54.   
  55.         {  
  56.   
  57.             Content = new StringContent(sb.ToString())  
  58.   
  59.         };  
  60.   
  61.     } catch (System.Exception e)  
  62.   
  63.     {  
  64.   
  65.         return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);  
  66.   
  67.     }  
  68.   
  69. }  
  70.   
  71. }  

Now, run the application to upload the files as in the following:

 
 
      

The API response in Firebug is shown here in the figure:

     
                    
Check, the file will be stored in the APP_DATA folder.
 
   
                                                                                       
We can upload multiple files also, as in the following figure.
 
  
 
Check the uploaded files In APP_DATA folder in the project.
 
  
                                                               
 
 
 
Uploading a file in Kendo UI using Generic Handler.

Create a generic handler by right-clicking on the project application, selecting Add, then New Item. Then select Generic Handler and name it AjaxFileUploader.ashx and click the Add button as shown in the following.

 
 
Write the following code in AjaxFileUploader.ashx:
  1. public class AjaxFileUploader: IHttpHandler,  
  2. IRequiresSessionState  
  3.   
  4. {  
  5.   
  6.     public void ProcessRequest(HttpContext context)  
  7.   
  8.     {  
  9.   
  10.         if (context.Request.Files.Count > 0)  
  11.   
  12.         {  
  13.   
  14.             string path = context.Server.MapPath("~/Images");  
  15.   
  16.             if (!Directory.Exists(path))  
  17.   
  18.             {  
  19.   
  20.                 Directory.CreateDirectory(path);  
  21.   
  22.             }  
  23.   
  24.             var file = context.Request.Files[0];  
  25.   
  26.             string fileName;  
  27.   
  28.             if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")  
  29.   
  30.             {  
  31.   
  32.                 string[] files = file.FileName.Split(new char[] {  
  33.                     '\\'  
  34.                 });  
  35.   
  36.                 fileName = files[files.Length - 1];  
  37.   
  38.             } else  
  39.   
  40.             {  
  41.   
  42.                 fileName = file.FileName;  
  43.   
  44.             }  
  45.   
  46.   
  47.             string fullFileNM = Path.Combine(path, fileName);  
  48.   
  49.             file.SaveAs(fullFileNM);  
  50.   
  51.   
  52.             string msg = "{";  
  53.   
  54.             msg += string.Format("error:'{0}',\n"string.Empty);  
  55.   
  56.             msg += string.Format("msg:'{0}',\n", fileName);  
  57.   
  58.             msg += "}";  
  59.   
  60.             context.Response.Write(msg);  
  61.   
  62.         }  
  63.   
  64.     }  
  65.   
  66.     public bool IsReusable  
  67.   
  68.     {  
  69.   
  70.         get  
  71.   
  72.         {  
  73.   
  74.             return true;  
  75.   
  76.         }  
  77.   
  78.     }  
  79.   
  80. }  

In the preceding code I have specified the path ~/Images where the uploaded images will be stored.

Write the following snippet in AyncUpload.html.

  1. <head>  
  2.     <title>Kendo Upload</title>  
  3.     <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.common.min.css">  
  4.         <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.default.min.css">  
  5.             <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.dataviz.min.css">  
  6.                 <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.dataviz.default.min.css">  
  7.                     <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>  
  8.                     <script src="http://cdn.kendostatic.com/2015.1.408/js/kendo.all.min.js"></script>  
  9.                 </head>  
  10.                 <body>  
  11.                     <div id="example">  
  12.                         <div class="demo-section k-header">  
  13.                             <div>  
  14.                                 <h4>Upload files</h4>  
  15.                                 <input name="files"  
  16.   
  17. type="file"  
  18.   
  19. data-role="upload"  
  20.   
  21. data-async="{ saveUrl: '/AjaxFileUploader.ashx', autoUpload: true }"  
  22.   
  23. data-bind="visible: isVisible,enabled: isEnabled">  
  24.                                 </div>  
  25.                             </div>  
  26.                         </div>  
  27.   
  28. Javascript:  
  29.   
  30. $(document).ready(function(){ var viewModel = kendo.observable({  
  31.   
  32. isEnabled: true,  
  33.   
  34. isVisible: true,  
  35.   
  36. });  
  37. kendo.bind($("#example"), viewModel);
  38. })

Now, run the application to upload the files as in the following figure.

Check the files in Image folder of your application.

 
Hurray! The image is stored in the respective folder.

I hope you have enjoyed this article, Thank you.

Happy Coding.


Similar Articles