Upload and Display Files Using MVC and AJAX

Introduction

This is a very simple article to upload and view documents using MVC and Ajax. Sometimes a user needs to upload file(s) to the server and view. For example, if you want to upload photos, PDF documents, text files and so on. This article shall help you to upload and view documents in a browser at the same time. Here I have created an Area (right-click on ProjectName (projStudentInfo) > add > Area) > Enter Area Name (DocumentViewAndUpload).

Then right-click on controller of that area and add controller with the name DocViewUpload.

So here we have Areas ->  DocumentViewAndUpload and controller DocViewUpload and View Index.cshtml.


Figure 1:
Solution Explorer 

Now in the controller we have an Index Action for which we have Index.cshtml in which we have a file upload control and a button.

Controller Code

  1. public ActionResult Index()   
  2. {  
  3.     return View();  
  4. }  
  5. [HttpPost]  
  6. public ActionResult Index(HttpPostedFileBase file)   
  7. {  
  8.     if (file != null && file.ContentLength > 0) try   
  9.     {  
  10.         string path = Path.Combine(Server.MapPath("~/Files"),  
  11.         Path.GetFileName(file.FileName));  
  12.         file.SaveAs(path);  
  13.         return Json(new {  
  14.             Error = false, Message = "File Uploaded Successfully..!!!", FilePath = file.FileName  
  15.         }, JsonRequestBehavior.AllowGet);  
  16.     }   
  17.     catch (Exception ex)   
  18.     {  
  19.         return Json(new {  
  20.             Error = false, Message = "File Not Uploaded"  
  21.         }, JsonRequestBehavior.AllowGet);  
  22.     }   
  23.     else   
  24.     {  
  25.         ViewBag.Message = "You have not specified a file.";  
  26.     }  
  27.     return View();  
  28. }  
  29. public FileResult ShowDocument(string FilePath)  
  30. {  
  31.     return File(Server.MapPath("~/Files/") + FilePath, GetMimeType(FilePath));  
  32. }  
  33. private string GetMimeType(string fileName)  
  34. {  
  35.     string mimeType = "application/unknown";  
  36.     string ext = System.IO.Path.GetExtension(fileName).ToLower();  
  37.     Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);  
  38.     if (regKey != null && regKey.GetValue("Content Type") != null)  
  39.     mimeType = regKey.GetValue("Content Type").ToString();  
  40.     return mimeType;  
  41. }  

In the preceding code we have an Index action and Index action with a HttpPostedFileBase parameter. On the click of the button a parameterized Index will be called. The code will copy a file to the “File” folder and the JSON result is returned to view the jQuery. JSON returns the filename to jQuery that then calls ShowDocument with file name as parameter. We have the GetMimeType function that returns ContentType as a string.

Index.cshtml

  1. @{  
  2. ViewBag.Title = "Index";  
  3. Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  5.   
  6. <h2>Document View And Upload</h2>  
  7. @using (Html.BeginForm("Index", "DocViewUpload", FormMethod.Post, new { @enctype = "multipart/form-data", @id = "MyForm" }))  
  8. {  
  9. <table border="0" cellpadding="0" cellspacing="0">  
  10.     <tr>  
  11.         <td>Please select File  
  12.         </td>  
  13.         <td>  
  14.             <input type="file" name="file" value="" id="myFile" />  
  15.         </td>  
  16.         <td></td>  
  17.     </tr>  
  18. </table>  
  19. }  
  20.   
  21. <button id="btnUpload">View Document</button>  
  22. <div id="DOC1"></div>  
  23. <script>  
  24.     $(document).ready(function () {  
  25.     $("#btnUpload").click(function () {  
  26.     if($("#myFile").val()=="")  
  27.     {  
  28.         alert("Please select a file");  
  29.         return false;  
  30.     }  
  31.     $('#MyForm').ajaxForm({  
  32.     complete: function (xhr) {  
  33.         var ret = $.parseJSON(xhr.responseText);  
  34.             if (ret.Error == false) {  
  35.             $("#DOC1").empty();  
  36.             $("#DOC1").html('  
  37.             <iframe src="@Url.Action("ShowDocument", "DocViewUpload", new { FilePath = "_FilePath" }) "'.replace("_FilePath", ret.FilePath) +  ' style="width: 98%; height: 98%" ></iframe>');  
  38.             // $("#DOC1").show();  
  39.             $("#DOC1").dialog({  
  40.             autoOpen: true,  
  41.             modal: true,  
  42.             height:500,  
  43.             width:600,  
  44.             buttons: {  
  45.                 OK: function () { $(this).dialog("close"); }  
  46.                 },  
  47.             title: "Document",  
  48.             });  
  49.         }  
  50.     },  
  51.     error: function () {  
  52.     window.location.reload();  
  53.     }  
  54. }).submit();  
  55. });  
  56. });  
  57. </script>  

NOTE:  Add the following reference code to _Layout.cshtml (master page).

For the ajaxForm function we need form.js in the script folder. 

  1. <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  
  2. <script src="//code.jquery.com/jquery-1.10.2.js"></script>  
  3. <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>  
  4. <script src="../../Scripts/form.js" type="text/javascript"></script>  

Remove @Scripts.Render("~/bundles/jquery") if you see in _Layout.cshtml.

Figure 2: Choose File 

Uploading Image file

Figure 3: File Uploading 
 
Thank you very much for reading.


Similar Articles