Uploading Files Using Strongly Typed FileUploader In ASP.NET MVC 5

Background

In earlier ASP.NET file upload control we needed to write lots of code to upload files, validate file extension and get files from upload control. Also lots of server resources were involved due to server control. Now in ASP.NET MVC we don't need to write lots of code. You can validate file extension and create html input file upload control using Data Annotation class without writing much code. So let us learn about the ASP.NET MVC strongly typed File Upload control step-by-step.

What is strongly typed control in ASP.NET MVC

The control which is created using model class property is called strongly typed control. Now let us demonstrate the preceding explanation by creating a sample ASP.NET MVC application as follows:

Step 1: Create an MVC Application.

Now let us start with a step by step approach from the creation of a simple MVC application as in the following:

  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".

  2. Click "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:


Step 2: Create Model Class

Now let us create the model class named FileUploadModel.cs by right clicking on Models folder as in the following screenshot:



Note: 

It is not mandatory that Model class should be in Model folder, it is just for better readability. You can create this class anywhere in the solution explorer. This can be done by creating different folder name or without folder name or in a separate class library.

FileUploadModel.cs class code snippet:
  1. public class FileUploadModel   
  2.   {    
  3.       [DataType(DataType.Upload)]    
  4.       [Display(Name = "Upload File")]    
  5.       [Required(ErrorMessage = "Please choose file to upload.")]    
  6.       public string file { getset; }    
  7.     
  8.   }   
Step 3 : Add Controller Class.

Now let us add the MVC 5 controller as in the following screenshot:


After clicking on Add button it will show the window. Specify the Controller name as FileUpload with suffix Controller.

Note:

The controller name must be having suffix as 'Controller' after specifying the name of controller. Now lets modify the default code in FileUploadController.cs to read uploaded files .

There are many ways to read the uploaded files in controller but in this article we will learn two ways to read the uploaded files into the controller which are listed below,
  • HttpRequestBase: We can use HttpRequestBase class property named Request to get collection of files or single file.
  • HttpPostedFileBase: This is the easiest way to read the uploaded files into the controller .
Now let's open the FileUploadController.cs class file and write the following code to read file using HttpRequestBase class.

Method 1 : Code snippet to read files using HttpRequestBase class as,
  1. [HttpPost]    
  2.        public ActionResult UploadFiles(HttpPostedFileBase file)    
  3.        {    
  4.            if (ModelState.IsValid)    
  5.            {    
  6.                try    
  7.                {    
  8.                    //Method 1 Get file details from current request    
  9.                    if (Request.Files.Count > 0)    
  10.                     {    
  11.                         var Inputfile = Request.Files[0];    
  12.     
  13.                         if (Inputfile != null && Inputfile.ContentLength > 0)    
  14.                         {    
  15.                             var filename = Path.GetFileName(Inputfile.FileName);    
  16.                           var path = Path.Combine(Server.MapPath("~/uploadedfile/"), filename);    
  17.                            Inputfile.SaveAs(path);    
  18.                        }    
  19.                     }    
  20.                     
  21.                    ViewBag.FileStatus = "File uploaded successfully.";    
  22.                }    
  23.                catch (Exception)    
  24.                {    
  25.     
  26.                    ViewBag.FileStatus = "Error while file uploading."; ;    
  27.                }    
  28.                 
  29.            }    
  30.            return View("Index");    
  31.        }   
Method 2 : Code snippet to read files using HttpPostedFileBase class as,
  1. [HttpPost]    
  2.        public ActionResult UploadFiles(HttpPostedFileBase file)    
  3.        {    
  4.            if (ModelState.IsValid)    
  5.            {    
  6.                try    
  7.                {    
  8.                      
  9.                    //Method 2 Get file details from HttpPostedFileBase class    
  10.     
  11.                    if (file != null)    
  12.                    {    
  13.                        string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));    
  14.                        file.SaveAs(path);     
  15.                    }    
  16.                    ViewBag.FileStatus = "File uploaded successfully.";    
  17.                }    
  18.                catch (Exception)    
  19.                {      
  20.                    ViewBag.FileStatus = "Error while file uploading."; ;    
  21.                }                  
  22.            }    
  23.            return View("Index");    
  24.        }  
Let's combine the code of both the methods in FileUploadController.cs file then the code will look like as follows,
  1. using System;    
  2. using System.IO;    
  3. using System.Web;    
  4. using System.Web.Mvc;    
  5.     
  6. namespace UploadingFilesUsingMVC.Controllers    
  7. {    
  8.     public class FileUploadController : Controller    
  9.     {    
  10.         // GET: FileUpload    
  11.         public ActionResult Index()    
  12.         {    
  13.             return View();    
  14.         }    
  15.         [HttpPost]    
  16.         public ActionResult UploadFiles(HttpPostedFileBase file)    
  17.         {    
  18.             if (ModelState.IsValid)    
  19.             {    
  20.                 try    
  21.                 {    
  22.                     //Method 1 Get file details from current request    
  23.                     //Uncomment following code if you wants to use method 1    
  24.                     //if (Request.Files.Count > 0)    
  25.                     // {    
  26.                     //     var Inputfile = Request.Files[0];    
  27.     
  28.                     //     if (Inputfile != null && Inputfile.ContentLength > 0)    
  29.                     //     {    
  30.                     //         var filename = Path.GetFileName(Inputfile.FileName);    
  31.                     //       var path = Path.Combine(Server.MapPath("~/uploadedfile/"), filename);    
  32.                     //        Inputfile.SaveAs(path);    
  33.                     //    }    
  34.                     // }    
  35.     
  36.                     //Method 2 Get file details from HttpPostedFileBase class    
  37.     
  38.                     if (file != null)    
  39.                     {    
  40.                         string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));    
  41.                         file.SaveAs(path);    
  42.     
  43.                     }    
  44.                     ViewBag.FileStatus = "File uploaded successfully.";    
  45.                 }    
  46.                 catch (Exception)    
  47.                 {    
  48.     
  49.                     ViewBag.FileStatus = "Error while file uploading.";    
  50.                 }    
  51.                  
  52.             }    
  53.             return View("Index");    
  54.         }    
  55.     }    
  56. }   
Step 4 : Creating strongly typed view named Index using FileUploadModel class .

Right click on View folder of created application and choose add view, select FileUploadModel class and create scaffolding template to create view to upload files as,



Click on Add button, then it will create the view named index. Now open the Index.cshtml view, then the following default code you will see which is generated by MVC scaffolding template as,

Index.cshtml

  1. @model UploadingFilesUsingMVC.Models.FileUploadModel    
  2.     
  3. @{    
  4.     ViewBag.Title = "www.compilemode.com";    
  5. }    
  6.     
  7. @using (Html.BeginForm("UploadFiles""FileUpload", FormMethod.Post,new { enctype = "multipart/form-data" }))    
  8. {    
  9.     @Html.AntiForgeryToken()    
  10.         
  11.     <div class="form-horizontal">    
  12.         <hr />    
  13.         @Html.ValidationSummary(true""new { @class = "text-danger" })    
  14.         <div class="form-group">    
  15.             @Html.LabelFor(model => model.file, htmlAttributes: new { @class = "control-label col-md-2" })    
  16.             <div class="col-md-10">    
  17.                 @Html.EditorFor(model => model.file, new { htmlAttributes = new { @class = "form-control", @type="file"} })    
  18.                 @Html.ValidationMessageFor(model => model.file, ""new { @class = "text-danger" })    
  19.             </div>    
  20.         </div>    
  21.             
  22.         <div class="form-group">    
  23.             <div class="col-md-offset-2 col-md-10">    
  24.                 <input type="submit" value="Upload" class="btn btn-primary" />    
  25.             </div>    
  26.         </div>    
  27.         <div class="form-group">    
  28.             <div class="col-md-offset-2 col-md-10 text-success">    
  29.                 @ViewBag.FileStatus    
  30.             </div>    
  31.         </div>    
  32.     </div>    
  33. }    
  34. <script src="~/Scripts/jquery-1.10.2.min.js"></script>    
  35. <script src="~/Scripts/jquery.validate.min.js"></script>    
  36. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>   
Step 4 : Create a folder named UploadedFiles or as you wish to save uploaded files,

Right click on created ASP.NET MVC application, solution explorer and choose add new item, then Add New Folder. After adding the model, view, controller and UploadedFiles folder to save the file. Solution explorer will look like as follows,


Now we have done all coding to upload files.

Step 5: Now run the application. After running the application initial screen will look as follows,

Now click on Upload button without selecting file then the following error message is visible which we have defined in model class as,


Now browse the file and click on upload button, It will show the following message after successfully uploading the file as,



Now lets see the UploadedFiles folder where our uploaded files are saved, Browse the folder or move the mouse cursor or image then uploaded image will look like as follows,



I hope from allthe preceding examples we have learned how to upload files using strongly typed file uploader in ASP.NET MVC .

Note:
  • HttpPostedFileBase instance name must be a file.
  • Model class property name must be file so it can generate the input type file .
  • Its important to define enctype = "multipart/form-data" in form action otherwise file value will be null in controller .
  • Download the Zip file of the sample application for a better understanding.
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
  • This application is created completely focusing on beginners.
Summary

I hope this article is useful for all readers. If you have any suggestions please contact me.

Read more articles on ASP.NET:


Similar Articles