Strongly Typed FileUploader In ASP.NET MVC 5

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:
public class FileUploadModel   
      {    
          [DataType(DataType.Upload)]    
          [Display(Name = "Upload File")]    
          [Required(ErrorMessage = "Please choose file to upload.")]    
          public string file { get; set; }    
        
      }   
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,
FileUploadController.cs

[HttpPost]    
           public ActionResult UploadFiles(HttpPostedFileBase file)    
           {    
               if (ModelState.IsValid)    
               {    
                   try    
                   {    
                       //Method 1 Get file details from current request    
                       if (Request.Files.Count > 0)    
                        {    
                            var Inputfile = Request.Files[0];    
        
                            if (Inputfile != null && Inputfile.ContentLength > 0)    
                            {    
                                var filename = Path.GetFileName(Inputfile.FileName);    
                              var path = Path.Combine(Server.MapPath("~/uploadedfile/"), filename);    
                               Inputfile.SaveAs(path);    
                           }    
                        }    
                        
                       ViewBag.FileStatus = "File uploaded successfully.";    
                   }    
                   catch (Exception)    
                   {    
        
                       ViewBag.FileStatus = "Error while file uploading."; ;    
                   }    
                    
               }    
               return View("Index");    
           }   
Method 2 : Code snippet to read files using HttpPostedFileBase class as,
[HttpPost]    
           public ActionResult UploadFiles(HttpPostedFileBase file)    
           {    
               if (ModelState.IsValid)    
               {    
                   try    
                   {    
                         
                       //Method 2 Get file details from HttpPostedFileBase class    
        
                       if (file != null)    
                       {    
                           string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));    
                           file.SaveAs(path);     
                       }    
                       ViewBag.FileStatus = "File uploaded successfully.";    
                   }    
                   catch (Exception)    
                   {      
                       ViewBag.FileStatus = "Error while file uploading."; ;    
                   }                  
               }    
               return View("Index");    
           }  
Let's combine the code of both the methods in FileUploadController.cs file then the code will look like as follows,
using System;    
    using System.IO;    
    using System.Web;    
    using System.Web.Mvc;    
        
    namespace UploadingFilesUsingMVC.Controllers    
    {    
        public class FileUploadController : Controller    
        {    
            // GET: FileUpload    
            public ActionResult Index()    
            {    
                return View();    
            }    
            [HttpPost]    
            public ActionResult UploadFiles(HttpPostedFileBase file)    
            {    
                if (ModelState.IsValid)    
                {    
                    try    
                    {    
                        //Method 1 Get file details from current request    
                        //Uncomment following code if you wants to use method 1    
                        //if (Request.Files.Count > 0)    
                        // {    
                        //     var Inputfile = Request.Files[0];    
        
                        //     if (Inputfile != null && Inputfile.ContentLength > 0)    
                        //     {    
                        //         var filename = Path.GetFileName(Inputfile.FileName);    
                        //       var path = Path.Combine(Server.MapPath("~/uploadedfile/"), filename);    
                        //        Inputfile.SaveAs(path);    
                        //    }    
                        // }    
        
                        //Method 2 Get file details from HttpPostedFileBase class    
        
                        if (file != null)    
                        {    
                            string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));    
                            file.SaveAs(path);    
        
                        }    
                        ViewBag.FileStatus = "File uploaded successfully.";    
                    }    
                    catch (Exception)    
                    {    
        
                        ViewBag.FileStatus = "Error while file uploading.";    
                    }    
                     
                }    
                return View("Index");    
            }    
        }    
    }   
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

@model UploadingFilesUsingMVC.Models.FileUploadModel

@{
    ViewBag.Title = "www.compilemode.com";
}

@using (Html.BeginForm("UploadFiles", "FileUpload", FormMethod.Post,new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.file, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.file, new { htmlAttributes = new { @class = "form-control", @type="file"} })
                @Html.ValidationMessageFor(model => model.file, "", new { @class = "text-danger" })
            </div>
        </div>
        
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Upload" class="btn btn-primary" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10 text-success">
                @ViewBag.FileStatus
            </div>
        </div>
    </div>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<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 all the 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 .
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
Summary
I hope this article is useful for all readers. If you have any suggestions please contact me.
Read more articles on ASP.NET Web API:

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode