FileUpload in ASP.Net MVC

In web development projects, file uploading is a very common feature. The question always arises of how to upload a file or how to create these kinds of features in MVC applications. This article explains how the FileUpload control works with MVC, how to upload a file, how to open an uploaded file and how to delete an uploaded file.

In simple HTML we define the FileUpload control like this:

  1. <input type="file" name="file_Uploader" />
ASP.NET-MVC1

This HTML control has a TextBox and a button. When you click on the button a file open dialog box will open automatically. You choose a file and your file path will apear in the text box, these features are built into the FileUpload control.

See the following code.

First we will create a model FileModel.cs with the following code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace MvcApplication1.Models  
  6. {  
  7.     public class FileUploadModel  
  8.     {  
  9.         public string FileName { getset; }  
  10.         public string FilePath { getset; }  
  11.     }  
  12. } 

In the code above we have the FileUploadModel class, in this class we have the following two auto implemented properties:

1. FileName
2. FilePath.

  1. Now add a new Controller FileUploadController.cs with the following code:

    1. publicActionResult FileUpload()  
    2. {  
    3.     return View();  
    4. }

  2. Now add a new view FileUpload.cshtml with the following code:

    1. @model MvcApplication1.Models.FileUploadModel  
    2. <script src="~/Scripts/jquery-1.9.1.min.js"></script>  
    3. <script type="text/javascript">  
    4.     $(document).ready(function () {  
    5.         if('@ViewBag.Message' == 'File Uploaded Successfully')  
    6.         {  
    7.             alert('File Uploaded Successfully');  
    8.         }  
    9.         if ('@ViewBag.Message' == 'File is already exists') {  
    10.             alert('File is already exists');  
    11.         }  
    12.         $('#uloadTable td img.link').live('click'function () {  
    13.             var filename = $(this).parent().parent().parent().attr('id');  
    14.             $(this).parent().parent().parent().remove();  
    15.             $.ajax({  
    16.                 type: "post",  
    17.                 url: "/FileUpload/RemoveUploadFile?fileName=" + filename,  
    18.                 datatype: "json",  
    19.                 traditional: true,  
    20.                 success: function (data) {  
    21.                     alert('File Deleted');  
    22.                     if (data == 0) {  
    23.                         $('#uloadTable').remove();  
    24.                     }  
    25.                 }  
    26.             });  
    27.         });  
    28.     });  
    29. </script>  
    30. @{  
    31.     ViewBag.Title = "FileUpload";  
    32. }  
    33. <h2>File Upload</h2>  
    34. @using (@Html.BeginForm("FileUpload""FileUpload", FormMethod.Post, new { @id = "form1", @enctype = "multipart/form-data" }))  
    35. {  
    36.     <table>  
    37.         <tr>  
    38.             <td>  
    39.                 <input type="file" name="file_Uploader" />  
    40.             </td>  
    41.             <td>  
    42.                 <input type="submit" id="bttn_Upload" value="Upload" />  
    43.             </td>  
    44.         </tr>  
    45.     </table>  
    46.     if (Session["fileUploader"] != null)  
    47.     {  
    48.     <div class="upload">  
    49.         <div style="width: 500px;">  
    50.             <table id="uloadTable" border="1">  
    51.                 <thead>  
    52.                     <tr>  
    53.                         <th>Name</th>  
    54.                         <th>Action</th>  
    55.                     </tr>  
    56.                 </thead>  
    57.                 <tbody>  
    58.                     @foreach (var item in (List<MvcApplication1.Models.FileUploadModel>)Session["fileUploader"])  
    59.                     {  
    60.                         <tr id="@item.FileName">  
    61.                             <td>@item.FileName</td>  
    62.                             <td style="text-align: center"><a class="viewc"  href="@Url.Action("OpenFile", "FileUpload", new { @fileName = item.FileName })">  
    63.                                 <img width="16" height="16" border="0" src="~/Images/view.png" class="viewc"></a>  
    64.                                 <a class="viewc" href="">  
    65.                                     <img width="16" height="16" border="0" src="~/Images/Delete.png" class="link"></a></td>  
    66.                         </tr>  
    67.                     }  
    68.                 </tbody>  
    69.             </table>  
    70.         </div>  
    71.     </div>  
    72.     }  
    73. }  

Here the important thing is that we need to remember always, when we work with the file upload control always add this with form tag @enctype = "multipart/form-data" as in the following:

  1. @using (@Html.BeginForm("FileUpload""FileUpload", FormMethod.Post, new { @id = "form1", @enctype = "multipart/form-data" }))  
Now create a new folder in your application, in this application I create MyFiles. And now add the following code in to "FileUploadController.cs".

  1. using MvcApplication1.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8. namespace FileUploader.Controllers  
  9. {  
  10.     public class FileUploadController : Controller  
  11.     {  
  12.         //  
  13.         // GET: /FileUpload/  
  14.         public ActionResult FileUpload()  
  15.         {  
  16.             return View();  
  17.         }  
  18.         [HttpPost]  
  19.         public ActionResult FileUpload(HttpPostedFileBase file_Uploader)  
  20.         {  
  21.             if (file_Uploader!=null)  
  22.             {  
  23.                 string fileName = string.Empty;  
  24.                 string destinationPath = string.Empty;  
  25.                 List<FileUploadModel> uploadFileModel = new List<FileUploadModel>();  
  26.                 fileName = Path.GetFileName(file_Uploader.FileName);  
  27.                 destinationPath = Path.Combine(Server.MapPath("~/MyFiles/"), fileName);  
  28.                 file_Uploader.SaveAs(destinationPath);  
  29.                 if (Session["fileUploader"] != null)  
  30.                 {  
  31.                     var isFileNameRepete = ((List<FileUploadModel>)Session["fileUploader"]).Find(x => x.FileName == fileName);  
  32.                     if (isFileNameRepete == null)  
  33.                     {  
  34.                         uploadFileModel.Add(new FileUploadModel { FileName = fileName, FilePath = destinationPath });  
  35.                         ((List<FileUploadModel>)Session["fileUploader"]).Add(new FileUploadModel { FileName = fileName, FilePath = destinationPath });  
  36.                         ViewBag.Message = "File Uploaded Successfully";  
  37.                     }  
  38.                     else  
  39.                     {  
  40.                         ViewBag.Message = "File is already exists";  
  41.                     }  
  42.                 }  
  43.                 else  
  44.                 {  
  45.                     uploadFileModel.Add(new FileUploadModel { FileName = fileName, FilePath = destinationPath });  
  46.                     Session["fileUploader"] = uploadFileModel;  
  47.                     ViewBag.Message = "File Uploaded Successfully";  
  48.                 }  
  49.             }  
  50.             return View();  
  51.         }  
  52.         [HttpPost]  
  53.         public ActionResult RemoveUploadFile(string fileName)  
  54.         {  
  55.             int sessionFileCount = 0;  
  56.             try  
  57.             {  
  58.                 if (Session["fileUploader"] != null)  
  59.                 {                   
  60.                     ((List<FileUploadModel>)Session["fileUploader"]).RemoveAll(x => x.FileName == fileName);  
  61.                     sessionFileCount = ((List<FileUploadModel>)Session["fileUploader"]).Count;  
  62.                     if (fileName != null || fileName != string.Empty)  
  63.                     {  
  64.                         FileInfo file = new FileInfo(Server.MapPath("~/MyFiles/" + fileName));  
  65.                         if (file.Exists)  
  66.                         {  
  67.                             file.Delete();  
  68.                         }  
  69.                     }  
  70.                 }  
  71.             }  
  72.             catch (Exception ex)  
  73.             {  
  74.                 throw ex;  
  75.             }  
  76.             return Json(sessionFileCount, JsonRequestBehavior.AllowGet);  
  77.         }  
  78.         public FileResult OpenFile(string fileName)  
  79.         {  
  80.             try  
  81.             {  
  82.                 return File(new FileStream(Server.MapPath("~/MyFiles/" + fileName), FileMode.Open), "application/octetstream", fileName);  
  83.             }  
  84.             catch (Exception ex)  
  85.             {  
  86.                 throw ex;  
  87.             }  
  88.         }  
  89.     }  
  90. }
Understand the code

  1. [HttpPost]  
  2. public ActionResult FileUpload(HttpPostedFileBase file_Uploader)  
  3. { 

Here we have the parameter HttpPostedFileBase, the question now arises of what it is.

HttpPostedFileBase is an abstract class that has the following properties that are helpful to determine everything about your selected file, that you chose from the file upload control

  1. Contentlength: Lenth of file

  2. Contenttype: Type of file

  3. FileName: Name of file

  4. InputStream: For reading the contents of file

This is also helpful for a "saveas" of your file into your server folder destination where you want to save it.

One thing to always remember is that when you declare a HttpPostedFileBase, the variable name should be the same as you gave as the name of your HTML control name as in the following example:

  1. public ActionResult FileUpload(HttpPostedFileBase file_Uploader)  

  1. <input type="file" name="file_Uploader" />

Both names are the same, "file_Uploader".

ASP.NET-MVC2

After uploading files:

ASP.NET-MVC3

If you upload a file with the same name then you will get an alert message saying it is not possible to load a file with the same name into the folder.

How to delete a file

  1. [HttpPost]  
  2. public ActionResult RemoveUploadFile(string fileName)  
  3. {  
  4.     int sessionFileCount = 0;  
  5.     try  
  6.     {  
  7.         if (Session["fileUploader"] != null)  
  8.         {  
  9.        ((List<FileUploadModel>)Session["fileUploader"]).RemoveAll(x => x.FileName == fileName);  
  10.             sessionFileCount = ((List<FileUploadModel>)Session["fileUploader"]).Count;  
  11.             if (fileName != null || fileName != string.Empty)  
  12.             {  
  13.                 FileInfo file = new FileInfo(Server.MapPath("~/MyFiles/" + fileName));  
  14.                 if (file.Exists)  
  15.                 {  
  16.                     file.Delete();  
  17.                 }  
  18.             }  
  19.         }  
  20.     }  
  21.     catch (Exception ex)  
  22.     {  
  23.         throw ex;  
  24.     }  
  25.     return Json(sessionFileCount, JsonRequestBehavior.AllowGet);  
  26. }  
  27. $('#uloadTable td img.link').live('click', function () {  
  28.     var filename = $(this).parent().parent().parent().attr('id');  
  29.     $(this).parent().parent().parent().remove();  
  30.     $.ajax({  
  31.         type: "post",  
  32.         url: "/FileUpload/RemoveUploadFile?fileName=" + filename,  
  33.         datatype: "json",  
  34.         traditional: true,  
  35.         success: function (data) {  
  36.             alert('File Deleted');  
  37.             if (data == 0) {  
  38.                 $('#uloadTable').remove();  
  39.             }  
  40.         }  
  41.     });  
  42. }); 

In the code above, we are sending the filename on a RemoveUploadFile action method.

url: "/FileUpload/RemoveUploadFile?fileName=" + filename,

This code will send the file name into your action parameter. If it finds the file name it will delete the file, from that folder.

  1. if (fileName != null || fileName != string.Empty)  
  2. {  
  3.     FileInfo file = new FileInfo(Server.MapPath("~/MyFiles/" + fileName));  
  4.     if (file.Exists)  
  5.     {  
  6.         file.Delete();  
  7.     }  
  8. }

So that's it. For any query please send your comments, I will definitely help you out. Happy Programming.


Similar Articles