FileUpload using Jquery in MVC

Let begin now.

Step 1: Create a View(uploadDocument.cshtml) in MVC and add below HTML table and add input type of type file.

  1. <table>  
  2.     <tr>  
  3.         <td>  
  4. Upload Document   
  5.             <span style="color: Red;">*</span>:  
  6.   
  7.         </td>  
  8.         <td style="width: 15%;">  
  9.             <input type="file" id="file" name="file" />  
  10.         </td>  
  11.     </tr>  
  12.     <tr>  
  13.         <td colspan="2" style="text-align: center;">  
  14.             <input type="button" class="btn btn-primary" name="Submit" id="Submit" value="Upload" />  
  15.     
  16.   
  17.             <input type="button" class="btn btn-primary" name="Reset" id="Cancel" value="Reset" />  
  18.         </td>  
  19.     </tr>  
  20. </table>  
Step 2: Add controller to MODEL name it as UploadConteroller.CS and then apply the logic to save uploaded fle.
  1. [HttpPost]  
  2. public JsonResult UploadDocument(HttpPostedFileBase File) {  
  3.     try {  
  4.   
  5.         var files = Request.Files[0];  
  6.         if (files != null && files.ContentLength > 0) {  
  7.             var path = Server.MapPath("~/Content/UploadedFiles/" + File.FileName); // Path to save the file.  
  8.             File.SaveAs(path);  
  9.         }  
  10.         return Json(“Uploaded the file”, JsonRequestBehavior.AllowGet);  
  11.     } catch (Exception ex) {  
  12.         return Json(ex.Message, JsonRequestBehavior.AllowGet);  
  13.     }  
  14. }  
Step 3: Now its time to work with JQuery.
  1. var data = new FormData(); // appending to form data.  
  2. var files = $("#file").get(0).files;  
  3. if (files.length > 0) {  
  4.     data.append("file", files[0]);  
  5. }  
  6.   
  7. $.ajax({  
  8.     type: "POST",  
  9.     dataType: "json",  
  10.     url: '@Url.Action("UploadDocument", "Upload")',  
  11.     contentType: false// Mandaitory to be false  
  12.     processData: false// Mandaitory to be false  
  13.     data: data, // Pass the data to controller as paramter.  
  14.     success: function(result) {  
  15.         alert(result);  
  16.   
  17.     },  
  18.     error: function(xhr, ajaxOptions, thrownError) {  
  19.         alert(result);  
  20.   
  21.     }  
  22. });  
I hope this would help developers & beginners. So start using and enjoy coding.