Dynamically Creating Multiple File Uploads In MVC And Validating It

In this article, we are going to learn how to create dynamic file upload and validate all files in MVC. If you Google for file upload examples in MVC, you will find many examples but all are for single file uploads. Here, we don’t want that. We want to generate dynamic file upload on the basis of condition.

You can think of  it as tailored file uploads

E.g. if a user is filling out a form for a new driving license, he is required to upload documents, like address proof [Passport] and personal identity etc. But meanwhile, if you are applying for a passport, then you may need a driving license and personal identity. For developing this, we are not going to create 2 different pages but we are going to create it dynamically, on a single page.

Multipel file uploads
Fig 1 Multiple file uploads.

Tools Required

  • SQL Server
  • Visual Studio 2010 and above with MVC installed.

Creating Multiple Uploads

Let's start with creating a basic MVC application

From Visual Studio IDE, select File Menu right at the top. Inside that, select New --> Project and click on Project.
After selecting Project sub menu, a new dialog will pop up with the name “New Project”. In this dialog, first we select template from the left panel. First select "web" in the left panel, then choose “ASP.NET MVC 4 Web Application”. Now, name your project as “MultipleUploads”.

Selecting Template
Fig 2. Selecting Template

Finally, click on OK button to create the project.

Selecting Templates

After you create a project, a new window will pop up with the name “New ASP.NET MVC 4 Project”. In this project template, just select Empty Template and in the View Engine, select Razor. Click on OK button.

Selecting MVC 4 Project
Fig 3. Selecting MVC 4 Project

After a few seconds, you project is ready to go. It contains a whole lot of MVC folder structures and other scripts and .CSS styles.

Project Structure after creation

Project structure
Fig 4. Project structure

Now, let’s start with adding Controller.

Adding Controller

After creating project, we are going to add Controller with the name DocumentsController which is going to handle http get [HttpGet] and post [HttpPost] requests.

Adding Documents Controller
Fig 5. Adding Documents Controller

After adding Controller, next we are going to add Model.

Adding Model

In this step, we are going to add Model with the name “DocumentModel”. This model will have properties, such as DocumentID, DocumentName, and Mandatory.

For adding Model, just right click on Models folder and select Add >> Class.

Adding DocumentModel
Fig 6. Adding DocumentModel

After selecting Class, a new dialog will pop up with the name “Add New Item”. Here, the class will be selected by default. All we need to do is give name to the class. We are going to name it as “DocumentModel”.

Adding DocumentModel
Fig 7. Adding DocumentModel

Code snippet of DocumentModel

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace MultipleUploads.Models  
  7. {  
  8.     public class DocumentModel  
  9.     {  
  10.         public int DocumentID { getset; }  
  11.         public string DocumentName { getset; }  
  12.         public int Mandatory { getset; }  
  13.         public List<DocumentModel> DocumentList { getset; }  
  14.     }  
  15. }  
Properties 
  • DocumentID is unique ID.
  • DocumentName is the name of document which we are going to show to users to provide input.
  • Mandatory is property which tells this file is Mandatory to upload or not.
  • DocumentList contains the list of documents which we are going to send to View to generate controls.

After adding Model, next we are going to change the Action Method name inside Document Controller to “Upload” from Index; and create another action method which is going to handle http post [HttpPost] request, and will take DocumentModel as input parameter.

Code snippet of Document Controller

  1. using MultipleUploads.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace MultipleUploads.Controllers  
  9. {  
  10.     public class DocumentsController : Controller  
  11.     {  
  12.         //  
  13.         // GET: /Documents/  
  14.         [HttpGet]  
  15.         public ActionResult Upload()  
  16.         {  
  17.             return View();  
  18.         }  
  19.   
  20.         [HttpPost]  
  21.         public ActionResult Upload(DocumentModel DocumentModel)  
  22.         {  
  23.             return View();  
  24.         }  
  25.     }  
  26. }  
After creating action method for handling both get and post methods, now we are going to fill collection of documents in http get request.

Populating Document Collection

In this step, we are going to fill collection which we are going to send to the View. Using this collection, we are going to create file upload controls on View.

Note: for displaying demo, I am going to fill collection in controller. If you want to populate this data from database, you can do it.

Code snippet of Document Controller
  1. using MultipleUploads.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace MultipleUploads.Controllers  
  9. {  
  10.     public class DocumentsController : Controller  
  11.     {  
  12.         //  
  13.         // GET: /Documents/  
  14.         [HttpGet]  
  15.         public ActionResult Upload()  
  16.         {  
  17.             DocumentModel objdocument = new DocumentModel();  
  18.   
  19.             objdocument.DocumentList = new List<DocumentModel>   
  20.             {   
  21.             new DocumentModel { DocumentID = 1,DocumentName ="PANCard", Mandatory=1 },  
  22.             new DocumentModel { DocumentID = 2,DocumentName ="IncomeTax", Mandatory=0},  
  23.             new DocumentModel { DocumentID = 3,DocumentName ="PassPortID", Mandatory=1 },  
  24.             new DocumentModel { DocumentID = 4,DocumentName ="Driving_Licence", Mandatory=1 }  
  25.             };  
  26.   
  27.             return View(objdocument);  
  28.         }  
  29.   
  30.         [HttpPost]  
  31.         public ActionResult Upload(DocumentModel DocumentModel)  
  32.         {  
  33.             return View();  
  34.         }  
  35.     }  
  36. }  
After completing with filling collection, now let’s View.

Adding View

For adding View, just right click inside upload Action Method and then select Add View from List.

Adding upload View
Fig 8. Adding upload View

After selecting, a new dialog will pop up with the name “Add View”. This View will have same name as Action Method name, as shown in the below snapshot. After that, we are going to choose View engine as Razor (CSHTML), then we have a checkbox to choose which is used for creating strongly typed View. Here, it asks for choosing model class. We are going to choose DocumentModel which is a Model that we have created. We have scaffolding template option to choose. Here, we are just going to keep it empty and then finally, we have to click on Add button to create View.

 Creating upload View
Fig 9. Creating upload View

Project Structure after adding View

Project structure after adding upload View
Fig 10. Project structure after adding upload View

After adding View, now we write the code on View to create multiple file upload controls.

Adding multiple file upload controls on View

In this step, we are going to generate multiple file upload control. For doing that, we use DocumentList model property which we are sending from Controller.

Code snippet
  1. @model MultipleUploads.Models.DocumentModel  
  2. @ {  
  3.     Layout = null;  
  4. }  
  5. Model which is going to received upload View.  
  6. Code snippet  
  7. @using(Html.BeginForm("Upload""Documents", FormMethod.Post, new {  
  8.     enctype = "multipart/form-data"  
  9. })) {}   

Html.BeginForm helper generates form tag and we have specified action name and controller name. Along with that, we are going to post this data. For that, we have used [ FormMethod.Post] method and at last enctype attribute to encoded data.

Note: The enctype attribute specifies how the form-data should be encoded when submitting it to the server.

Code snippet of upload View

  1. if (Model.DocumentList != null)  
  2. {  
  3.     for (int i = 0; i < Model.DocumentList.Count; i++)  
  4.     {  
  5.         var fileupload1 = "file_" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  6.         var hdnlbl1 = "hdnlbl_" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  7.         var hdn1 = "hdn1_" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  8.         var madname = "manddocname_" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  9.         var valdation = "_val" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  10.   
  11.   
  12.         if (Model.DocumentList[i].Mandatory != null)  
  13.         {  
  14.             var mad = "mand_" + i;  
  15.             @Html.HiddenFor(m => m.DocumentList[i].Mandatory, new { id = mad })  
  16.         }  
  17.   
  18.         @{ var documentname = Model.DocumentList[i].DocumentName;}  
  19.   
  20.                  
  21.         @Html.HiddenFor(m => m.DocumentList[i].DocumentName, new { id = hdnlbl1 })  
  22.         @Html.HiddenFor(m => m.DocumentList[i].DocumentID, new { id = hdn1 })  
  23.         @Html.HiddenFor(m => m.DocumentList[i].DocumentName, new { id = madname })  
  24.   
  25.         <div class="row">  
  26.             <div class="col-md-3">  
  27.                 @if (Model.DocumentList[i].Mandatory == 1)  
  28.                 {  
  29.                     <label style="color: red;">*</label>  
  30.                 }  
  31.                                   
  32.                <label style="font-size: 15px;">@documentname</label>  
  33.                 <span class="btn btn-info btn-file">  
  34.                     <input type="file" id="@fileupload1" name="@fileupload1"   
  35.                         onchange="ValidateFile(this);" />  
  36.                 </span>  
  37.                 <span style="color:Red" id=@valdation></span>  
  38.           
  39.             </div>  
  40.         </div>  
  41. <br />  
  42.     }  
  43. }
In this part, we are going to check if the Model which we are going to send is Null or not. After that, we use for loop to iterate and generate file upload control for list of documents sent from upload Action method [httpGet].
  1. if (Model.DocumentList != null)  
  2. {  
  3.     for (int i = 0; i < Model.DocumentList.Count; i++)  
  4.     {  
  5.    
  6.     }               
  7. }   
Then, we are generating unique id for assigning to controls because we should have unique id generated for each control to recognize it.
  1. var fileupload1 = "file_" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  2. var hdnlbl1 = "hdnlbl_" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  3. var hdn1 = "hdn1_" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  4. var madname = "manddocname_" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  5. var valdation = "_val" + Convert.ToString(Model.DocumentList[i].DocumentID);  
After generating unique id, we are going to assign this id to hidden fields which will help us receive data at Action method level after post data to Server.
  1. if (Model.DocumentList[i].Mandatory != null)  
  2. {  
  3.      var mad = "mand_" + i;  
  4.          @Html.HiddenFor(m => m.DocumentList[i].Mandatory, new { id = mad })  
  5. }  
  6.   
  7. @{ var documentname = Model.DocumentList[i].DocumentName;}  
  8.   
  9.          
  10. @Html.HiddenFor(m => m.DocumentList[i].DocumentName, new { id = hdnlbl1 })  
  11. @Html.HiddenFor(m => m.DocumentList[i].DocumentID, new { id = hdn1 })  
  12. @Html.HiddenFor(m => m.DocumentList[i].DocumentName, new { id = madname })  
After assigning value to hidden fields, now we are going to create file upload control, label for displaying document name, and also we are showing asterisk mark if document id mandatory.
  1. <div class="row">  
  2.     <div class="col-md-3">  
  3.         @if (Model.DocumentList[i].Mandatory == 1)  
  4.         {  
  5.             <label style="color: red;">*</label>  
  6.         }  
  7.         @{ var documentname = Model.DocumentList[i].DocumentName;}  
  8.         <label style="font-size: 15px;">@documentname</label>  
  9.         <span class="btn btn-info btn-file">  
  10.             <input type="file" id="@fileupload1" name="@fileupload1"   
  11.                 onchange="ValidateFile(this);" />  
  12.         </span>  
  13.         <span style="color:Red" id=@valdation></span>  
  14.   
  15.     </div>  
  16. </div>  
  17. Finally we require submit but to post form to server.  
  18.  <div style="margin-top: 20px;" class="col-sm-4 col-xs-12 col-lg-6 col-md-4">  
  19.   
  20.   <input id="Submit1" class="btn btn-success" type="submit"  
  21.                       onclick="return Savefiles();" value=" submit" />  
  22.   
  23.  </div>  
Code snippet of upload View
  1. <div class="container">  
  2.     <div style="margin-top: 20px;" class="row">  
  3.         <div class="col-sm-4 col-xs-12 col-lg-6 col-md-4">  
  4.         </div>  
  5.     </div>  
  6.     <div class="panel panel-default">  
  7.         <div class="panel-heading">@Html.Label("Upload Documents")</div>  
  8.         <div class="panel-body">  
  9.             @using (Html.BeginForm("Upload""Documents", FormMethod.Post,   
  10.                         new { id = "TheForm", enctype = "multipart/form-data" }))  
  11.             {  
  12.   if (Model.DocumentList != null)  
  13.   {  
  14.       for (int i = 0; i < Model.DocumentList.Count; i++)  
  15.       {  
  16.    var fileupload1 = "file_" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  17.    var hdnlbl1 = "hdnlbl_" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  18.    var hdn1 = "hdn1_" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  19.      
  20.    if (Model.DocumentList[i].Mandatory != null)  
  21.    {  
  22.        var mad = "mand_" + i;  
  23.        @Html.HiddenFor(m => m.DocumentList[i].Mandatory, new { id = mad })  
  24.    }  
  25.      
  26.    var madname = "manddocname_" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  27.    var valdation = "_val" + Convert.ToString(Model.DocumentList[i].DocumentID);  
  28.      
  29.    @Html.HiddenFor(m => m.DocumentList[i].DocumentName, new { id = hdnlbl1 })  
  30.    @Html.HiddenFor(m => m.DocumentList[i].DocumentID, new { id = hdn1 })  
  31.    @Html.HiddenFor(m => m.DocumentList[i].DocumentName, new { id = madname })  
  32.   
  33.   <div class="row">  
  34.       <div class="col-md-3">  
  35.           @if (Model.DocumentList[i].Mandatory == 1)  
  36.           {  
  37.               <label style="color: red;">*</label>  
  38.           }  
  39.           @{ var documentname = Model.DocumentList[i].DocumentName;}  
  40.           <label style="font-size: 15px;">@documentname</label>  
  41.           <span class="btn btn-info btn-file">  
  42.               <input type="file" id="@fileupload1" name="@fileupload1"   
  43.                   onchange="ValidateFile(this);" />  
  44.           </span>  
  45.           <span style="color:Red" id=@valdation></span>  
  46.     
  47.       </div>  
  48.   </div>  
  49.    <br />  
  50.        }  
  51.    }  
  52.    <div class="row">  
  53.        <div class="col-sm-4 col-xs-12 col-lg-6 col-md-4">  
  54.        </div>  
  55.    </div>  
  56.    <div style="margin-top: 20px;" class="col-sm-4 col-xs-12 col-lg-6 col-md-4">  
  57.        <input id="Submit1" class="btn btn-success" type="submit" onclick="return Savefiles();" value=" submit" />  
  58.    </div>  
  59.             }  
  60.         </div>  
  61.     </div>  
  62. </div>  
After we have generated control, let's have a look at how it gets rendered on the browser.

Upload View Rendered in browser
Fig 11. Upload View Rendered in browser

Now, we have just generated controls but we are not done with validation yet. So, let’s get started with it.

Validating File upload controls

For doing validation, we are going to use JavaScript.
  1. We are going to check file extension [is this file .png ,jpg, jpeg, .pdf]
  2. Size of file which is uploaded [Must be under 1 MB]
  3. Is file mandatory [the file declare as mandatory id must to upload]

Now, for doing this stuff, we need jQuery library.

Download: http://code.jquery.com/jquery-1.9.1.js
Download: http://code.jquery.com/jquery-migrate-1.2.1.js

We are going to validate file first. For doing this, we have used onchange event of JavaScript, when any one selects a file, this event gets called and mean while it is sending selected file upload id to the function.

After function receives file upload id, it will call another function [getNameFromPath] which returns file path. Now, from file path, we are going to extract extension and check if the extension is valid or not. If not, then we display error Message [You can upload only jpg, jpeg, png, pdf extension file Only] else we are going check size of the file uploaded by calling a function [ValidateFileSize]. If this is also not valid, then show the message [You Can Upload file Size Up to 1 MB] and then, remove the selected file.

  1. <input type="file" id="@fileupload1" name="@fileupload1" onchange="ValidateFile(this);" />  
Complete Code Snippet for validating uploaded file,
  1. function ValidateFile(value)   
  2. {  
  3.   
  4.         var file = getNameFromPath($(value).val());  
  5.         if (file != null) {  
  6.             var extension = file.substr((file.lastIndexOf('.') + 1));  
  7.             switch (extension) {  
  8.                 case 'jpg':  
  9.                 case 'jpeg':  
  10.                 case 'png':  
  11.                 case 'pdf':  
  12.                     flag = true;  
  13.                     break;  
  14.                 default:  
  15.                     flag = false;  
  16.             }  
  17.         }  
  18.   
  19.         if (flag == false)   
  20.         {  
  21.   
  22.             var str = value.name;  
  23.             var res = str.split("_");  
  24.             var data = "_val" + res[1];  
  25.             $("#" + data).text("You can upload only jpg, jpeg, png, pdf extension file Only");  
  26.             $("#" + value.name).val('');  
  27.             return false;  
  28.         }  
  29.         else   
  30.         {  
  31.             var size = ValidateFileSize(value);  
  32.             var str = value.name;  
  33.             var res = str.split("_");  
  34.             var data = "_val" + res[1];  
  35.             if (size > 1)   
  36.             {  
  37.                 $("#" + data).text("You Can Upload file Size Up to 1 MB.");  
  38.                 $("#" + value.name).val('');  
  39.             }  
  40.             else   
  41.             {  
  42.                 $("#" + data).text("");  
  43.             }  
  44.         }  
  45.     } 
Complete Code Snippet for getting file name of uploaded file,
  1. function getNameFromPath(strFilepath)   
  2. {  
  3.     var objRE = new RegExp(/([^\/\\]+)$/);  
  4.     var strName = objRE.exec(strFilepath);  
  5.   
  6.     if (strName == null) {  
  7.         return null;  
  8.     }  
  9.     else {  
  10.         return strName[0];  
  11.     }  
  12. }  
Complete Code Snippet for getting file size of uploaded file,
  1. function ValidateFileSize(fileid) {  
  2.         try {  
  3.             var fileSize = 0;  
  4.             if (navigator.userAgent.match(/msie/i)) {  
  5.                 var obaxo = new ActiveXObject("Scripting.FileSystemObject");  
  6.                 var filePath = $("#" + fileid)[0].value;  
  7.                 var objFile = obaxo.getFile(filePath);  
  8.                 var fileSize = objFile.size;  
  9.                 fileSize = fileSize / 1048576;   
  10.             }  
  11.             else {  
  12.                 fileSize = $(fileid)[0].files[0].size  
  13.                 fileSize = fileSize / 1048576;    
  14.             }  
  15.   
  16.             return fileSize;  
  17.         }  
  18.         catch (e) {  
  19.             alert("Error is :" + e);  
  20.         }  
  21.     }  
After validating all files, finally on submit button we are going to check if mandatory files are uploaded or not.
  1. <input id="Submit1" class="btn btn-success" type="submit" onclick="return Savefiles();"   
  2.   value=" submit" />  
  3. Complete Code for checking mandatory files  
  4. <script type="text/javascript">  
  5.   
  6.     function Savefiles() {  
  7.         var MandFlg = $("[id*='mand_']");  
  8.         var FileUpload1 = $("[id*='file_']");  
  9.         var madfile = $("[id*='manddocname_']");  
  10.         var Booleandata = true;  
  11.         for (var i = 0; i < MandFlg.length; i++) {  
  12.             if ($("#" + MandFlg[i].id).val() == '1' && $("#" + FileUpload1[i].id).val() == '') {  
  13.                 Booleandata = false;  
  14.                 alert("Required  " + $("#" + madfile[i].id).val());  
  15.             }  
  16.         }  
  17.         return Booleandata;  
  18.     }  
  19.   
  20. </script>  
Upload View with all functionality
Fig 12. Upload View with all functionality

Now, if everything is valid, then it will post form to the server else it will show error message.

After posting form, “upload” [HttpPost] action method will get called and it will receive all files which are posted, as shown below.

Posted data from View to Upload Action method
Fig 13. Posted data from View to Upload Action method

In upload action method, we are just going to receive files and according to our requirement we are going to store this file. If someone wants to save the files in a folder, they can do that. Meanwhile if some one wants in bytes, they too can store bytes in database.

Complete Code snippet of upload [HttpPost] Action Method.
  1. [HttpPost]  
  2. public ActionResult Upload(DocumentModel DocumentModel)  
  3. {  
  4.     var DocumentUpload = DocumentModel.DocumentList;  
  5.     foreach (var Doc in DocumentUpload)  
  6.     {  
  7.         string strFileUpload = "file_" + Convert.ToString(Doc.DocumentID);  
  8.         HttpPostedFileBase file = Request.Files[strFileUpload];  
  9.   
  10.         if (file != null && file.ContentLength > 0)  
  11.         {  
  12.             // if you want to save in folder use this  
  13.             var fileName = Path.GetFileName(file.FileName);  
  14.             var path = Path.Combine(Server.MapPath("~/Images/"), fileName);             
  15.             file.SaveAs(path);   
  16.   
  17.             // if you want to store in Bytes in Database use this  
  18.             byte[] image = new byte[file.ContentLength];  
  19.             file.InputStream.Read(image, 0, image.Length);   
  20.   
  21.         }  
  22.     }  
  23.     return View(DocumentModel);  
  24. }  
Thanks for taking the time to read this article.


Similar Articles