ASP.NET MVC Async File Uploading Using JQuery

Introduction

In this post, you will learn how to upload file in ASP.NET MVC without reloading the whole page or without refreshing the whole page. Instead we will update specific portion of page which is normally said async postback in web form terms.

Upload

Background

Once upon a time, I came across scenario where I needed to upload file in my ASP.NET MVC web application but it’s quite simple if we want full post-back, but I was thinking of doing it using Ajax by doing Partial Post-back.

Using JQuery to post standard forms is extremely simple, but when posting multi-part forms for uploading files it's not so intuitive. This is due to browser security restrictions and sandboxing. Today I'm going to show you how to fake an asynchronous upload without reloading the page and get a result back from the server.

First idea that came in my mind was using MVC helper Ajax.BeginForm and I came to know that it not support file upload by partial post-back, it will do post-back.

Second idea that was in my mind is to use JQuery and AJAX to post file on server so that I can avoid post-back, I tried my own way by posting file and returning partial view via AJAX but same issue was happening the partial view was rendering independently not on the same view, then I searched on internet and found a way.

This method uses IFrame and do a fake async postback and it looks like that file uploading via Ajax, as our view remains same.

How It Works

In order to make the AJAX style file uploads work, we need to to post to an iFrame. We're going to position an iFrame off the page to hide it and then post to it. We'll return a partial view to the page and append it in some html container. It's important to note that due to security limitations, the page being posted to must be on the same domain as the page you're posting from. Also, this solution will be using a single hidden iFrame, but for multiple simultaneous uploads you could dynamically generate the iFrames and post to them.

Main View

Here is my view code i have created a form using MVC Helper and after the form I added an iframe in which our form will be posted:

  1. @  
  2. {  
  3.     ViewBag.Title = "Ajax File Uploading";  
  4.     Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }   
  6. < h2 > Ajax File Uploading < /h2>  
  7. < div >  
  8. < div >  
  9.     < h1 > Upload File < /h1>  
  10. < /div>  
  11. @using(Html.BeginForm("Upload""Home", FormMethod.Post, new  
  12. {  
  13.     enctype = "multipart/form-data",  
  14.         id = "ImgForm",  
  15.         name = "ImgForm",  
  16.         target = "UploadTarget"  
  17. }))  
  18. {  
  19.     @ * DataBase Record ID as Hidden Field against which we are uplaoding file * @  
  20.     @Html.Hidden("ID", 65512) < div style = "width: 100px; margin: auto; float: left; line-height: 30px; font-weight: bold;" > File < /div>< div style = "width: 200px; float: left; margin: auto;" >< input type = "file"  
  21.     id = "uploadFile"  
  22.     name = "file"  
  23.     data - val = "true"  
  24.     data - val - required = "please select a file" / >< span id = "validityMessages"  
  25.     style = "color: Red;" >< /span>< /div>< div style = "clear: both;" >< /div>< div style = "width: auto; margin-top: 3%;" >< div style = "margin: 5% 18%;" >< input id = "upload"  
  26.     type = "button"  
  27.     value = "Upload"  
  28.     name = "Upload"  
  29.     onclick = "UploadImage()" / >< span id = "uploadLoader"  
  30.     style = "display: none;" >< img id = "searchLoader"  
  31.     src = "@Url.Content("~/Content/Images / loader.gif ")" / > Uploading Please Wait < /span>< /div>< /div>  
  32. }   
  33. < div id = "uploadsContainer" >< /div>  
  34. < iframe id = "UploadTarget"  
  35. name = "UploadTarget"  
  36. onload = "UploadImage_Complete();"  
  37. style = "position: absolute; left: -999em; top: -999em;" >< /iframe>< /div>  
  38. @section Scripts  
  39. { < script type = "text/javascript" > $(document)  
  40.         .ready(function ()  
  41.         {  
  42.             $('img.delUpload')  
  43.                 .live('click', function ()  
  44.                 {  
  45.                     var Id = this.id;  
  46.                     var url = '@Url.Action("DeleteFile","Home")';  
  47.                     url = url + "?id=" + Id  
  48.                     $.get(url, function (response)  
  49.                     {  
  50.                         $('#uploadsContainer')  
  51.                             .html(response);  
  52.                     });  
  53.                 });  
  54.         }); < /script>< script type = "text/javascript" >  
  55.         var isFirstLoad = true;  
  56.   
  57.     function UploadImage()  
  58.     {  
  59.         // check for size of file not greater than 1MB  
  60.         if ($("#uploadFile")  
  61.             .val())  
  62.         {  
  63.             var iSize = ($("#uploadFile")[0].files[0].size / 1024);  
  64.             iSize = (Math.round((iSize / 1024) * 100) / 100);  
  65.             if (iSize > 4)  
  66.             {  
  67.                 alert("File must be less than 4MB");  
  68.                 $('span#validityMessages')  
  69.                     .html("File must be less than 4MB");  
  70.                 return;  
  71.             }  
  72.             else  
  73.             {  
  74.                 // on form post showing Busy Indicator  
  75.                 $('#uploadLoader')  
  76.                     .show();  
  77.                 $("#ImgForm")  
  78.                     .submit(); // post form  
  79.                 console.log(iSize + "Mb");  
  80.             }  
  81.         }  
  82.         // check for no file selected for upload  
  83.         else  
  84.         {  
  85.             $('span#validityMessages')  
  86.                 .html("Please select a File of size less than 4MB!");  
  87.             return;  
  88.         }  
  89.     }  
  90.   
  91.     function UploadImage_Complete()  
  92.     {  
  93.         //Check to see if this is the first load of the iFrame  
  94.         if (isFirstLoad == true)  
  95.         {  
  96.             isFirstLoad = false;  
  97.         }  
  98.         $('#uploadLoader')  
  99.             .hide();  
  100.         //Reset the image form so the file won't get uploaded again  
  101.         document.getElementById("ImgForm")  
  102.             .reset();  
  103.         // this call will get uploads if any exists on server against this id and after successfull upload refreshing partial view to get the latest uploads  
  104.         GetFiles();  
  105.     }  
  106.   
  107.     function GetFiles()  
  108.     {  
  109.         var url = '@Url.Action("GetFiles","Home")';  
  110.         var Id = $('input#ID')  
  111.             .val();  
  112.         url = url + "?id=" + Id  
  113.         $.get(url, function (response)  
  114.         {  
  115.             $('#uploadsContainer')  
  116.                 .html(response);  
  117.         });  
  118.     } < /script>  
  119. }  
  120. Uploads ViewModel  
  121. Here is my uploads view model which is strongly typed with the uploads partial view: public class UploadsViewModel  
  122. {  
  123.     public long ID  
  124.     {  
  125.         get;  
  126.         set;  
  127.     }  
  128.     public List Uploads  
  129.     {  
  130.         get;  
  131.         set;  
  132.     }  
  133.     public UploadsViewModel()  
  134.     {  
  135.         this.Uploads = new List();  
  136.     }  
  137. }  
  138. public class File  
  139. {  
  140.     public string FilePath  
  141.     {  
  142.         get;  
  143.         set;  
  144.     }  
  145.     public long FileID  
  146.     {  
  147.         get;  
  148.         set;  
  149.     }  
  150.     public string FileName  
  151.     {  
  152.         get;  
  153.         set;  
  154.     }  
  155. }  
Upload Controller Method

Here is my controller method, I am taking two parameters input one is the posted form, in form I am posting some values in hidden fields required for DB updates and second parameter is posted file. I am simply saving the file in Uploads directory on server and updating a table in DB using Entity Framework and at the end returning partial view which will display the uploaded file name, thumbnail if it’s an image type file and button for deleting the file.

For this post I am storing the state in Session,
  1. [HttpPost]  
  2. public ActionResult Upload(FormCollection form, HttpPostedFileBase file)  
  3. {  
  4.     UploadsViewModel uploadsViewModel = Session["Uploads"] != null ? Session["Uploads"as UploadsViewModel : new UploadsViewModel();  
  5.     uploadsViewModel.ID = long.Parse(form["id"]);  
  6.     File upload = new File();  
  7.     upload.FileID = uploadsViewModel.Uploads.Count + 1;  
  8.     upload.FileName = file.FileName;  
  9.     upload.FilePath = "~/Uploads/" + file.FileName;  
  10.     //if (file.ContentLength < 4048576) we can check file size before saving if we need to restrict file size or we can check it on client side as well  
  11.     //{  
  12.     if (file != null)  
  13.     {  
  14.         file.SaveAs(Server.MapPath(upload.FilePath));  
  15.         uploadsViewModel.Uploads.Add(upload);  
  16.         Session["Uploads"] = uploadsViewModel;  
  17.     }  
  18.     // Save FileName and Path to Database according to your business requirements  
  19.     //}  
  20.     return PartialView("~/Views/Shared/_UploadsPartial.cshtml", uploadsViewModel.Uploads);  
  21. }  
Uploads Partial View

Here is my partial view code,
  1. @model List < AjaxFileUploading.ViewModels.File > @  
  2. {  
  3.     Layout = null;  
  4.     var IsAnyImage = Model.Any(x => new String[]  
  5.     {  
  6.         "jpg",  
  7.         "jpeg",  
  8.         "png",  
  9.         "gif"  
  10.     }.Contains(x.FileName.Split('.')  
  11.         .Last()));  
  12. }  
  13. @if(Model.Any())  
  14. { < h3 > Uploads < /h3> < hr / > < table style = "width: 500px;" > < tr > @if(IsAnyImage)  
  15.     { < th > Thumbnail < /th>  
  16.     } < th > FileName < /th> < th > Action < /th> < /tr> < tbody > @for(int i = 0; i < Model.Count; i++)  
  17.     { < tr > < td style = "text-align: center;" > < img width = "60"  
  18.         src = "@Url.Content(Model[i].FilePath)" / > < /td> < td style = "text-align: center;" > < a href = "@Url.Content("~/Uploads/  
  19.         " + Model[i].FileName)"  
  20.         target = "_blank" > @Model[i].FileName < /a></td > < td style = "text-align: center;" > < img id = "@Model[i].FileID"  
  21.         class = "delUpload"  
  22.         width = "20"  
  23.         src = "@Url.Content("~/Content/Images / delete.png ")" / > < /td> < /tr>  
  24.     } < /tbody> < /table>  
  25. }  
  26. else  
  27. { < h3 > No Uploads Found! < /h3>  
  28. }  
JavaScript and Query for MainView

The first thing we need to do is include a version of jQuery. Since I'm writing an MVC application, I've chosen to use bundles that are provided by the framework, so you will see the following line written in master layout _Layout.cshtml which is located in Views >> Shared directory:

  1. @Scripts.Render("~/bundles/jquery")  

Now we can start creating our JavaScript to handle our form posts. The UploadImage() method isn't absolutely necessary since all our example does is post the form, however as in my case i am displaying a busy indicator so that user acknowledged that file is uploading. Here we're just going to create a global variable that tells whether or not we're on the first load of the iFrame and the function to upload the image:

Now the form is setup to post to our iFrame. Here is the code which checks if any file exists against this record already it is displayed and validation is also applied in this event, actually this event will be called when iframe will load, on first page load also iframe load event is called so that’s why i have put validation code as well here, i am just checking by flag is it a first load of iFrame or not, if it's not first load then it means user is uploading file and we may want to validate on file size. I am not allowing file greater than 4MB, you can also check here for file extension as well, maybe you just want to allow user to upload images so in this function you can check that as well if you want to check on specific type of files to be just uploaded:
  1. <script type="text/javascript">  
  2. var isFirstLoad = true;  
  3.   
  4. function UploadImage()  
  5. {  
  6.     // check for size of file not greater than 1MB  
  7.     if ($("#uploadFile")  
  8.         .val())  
  9.     {  
  10.         var iSize = ($("#uploadFile")[0].files[0].size / 1024);  
  11.         iSize = (Math.round((iSize / 1024) * 100) / 100);  
  12.         if (iSize > 4)  
  13.         {  
  14.             alert("File must be less than 4MB");  
  15.             $('span#validityMessages')  
  16.                 .html("File must be less than 4MB");  
  17.             return;  
  18.         }  
  19.         else  
  20.         {  
  21.             // on form post showing Busy Indicator  
  22.             $('#uploadLoader')  
  23.                 .show();  
  24.             console.log(iSize + "Mb");  
  25.         }  
  26.     }  
  27.     // check for no file selected for upload  
  28.     else  
  29.     {  
  30.         $('span#validityMessages')  
  31.             .html("Please select a File of size less than 4MB!");  
  32.         return;  
  33.     }  
  34. }  
  35.   
  36. function UploadImage_Complete()  
  37. {  
  38.     //Check to see if this is the first load of the iFrame  
  39.     if (isFirstLoad == true)  
  40.     {  
  41.         isFirstLoad = false;  
  42.     }  
  43.     $('#uploadLoader')  
  44.         .hide();  
  45.     //Reset the image form so the file won't get uploaded again  
  46.     document.getElementById("ImgForm")  
  47.         .reset();  
  48.     // this call will get uploads if any exists on server against this id and after successfull upload refreshing partial view to get the latest uploads  
  49.     GetFiles();  
  50. }  
  51. </script> And at last here is the deleting of file using ajax: $(document).ready(function () { $('img.delUpload').live('click', function () { var Id = this.id; var url = '@Url.Action("DeleteFile","Home")'; url = url + "?id=" + Id $.get(url, function (response) { $('#uploadsContainer').html(response); }); }); });  
Delete File Controller Method

Here is the Delete File Action,
  1. public ActionResult DeleteFile(long id)  
  2. {  
  3.     /* Use input Id to delete the record from db logically by setting IsDeleted bit in your table or delete it physically whatever is suitable for you 
  4.     for DEMO purpose i am stroing it in Session */  
  5.     UploadsViewModel viewModel = Session["Uploads"as UploadsViewModel;  
  6.     File file = viewModel.Uploads.Single(x => x.FileID == id);  
  7.     try  
  8.     {  
  9.         System.IO.File.Delete(Server.MapPath(file.FilePath));  
  10.         viewModel.Uploads.Remove(file);  
  11.     }  
  12.     catch (Exception)  
  13.     {  
  14.         return PartialView("~/Views/Shared/_UploadsPartial.cshtml", viewModel.Uploads);  
  15.     }  
  16.     return PartialView("~/Views/Shared/_UploadsPartial.cshtml", viewModel.Uploads);  
  17. }  
And GetFiles actions looks like the following,
  1. public ActionResult GetFiles(long Id)  
  2. {  
  3.    UploadsViewModel viewModel = Session["Uploads"as UploadsViewModel;  
  4.   
  5.    return PartialView("~/Views/Shared/_UploadsPartial.cshtml", (viewModel == null ? new UploadsViewModel().Uploads : viewModel.Uploads));  
  6. }  
I have created a sample project to demonstrate it. The screenshot is attached,
run

Hope you will get the understanding how it’s working, for reference from where i got help you can also visit this link for more details: AJAX File Uploads with jQuery and MVC 3.

You can download sample source code from here.
Download Source Code (AjaxFileUploading.zip). 

Up Next
    Ebook Download
    View all
    Learn
    View all