Uploading Multiple Files In ASP.NET MVC

Background
 
Many times, we need to upload multiple files at a time in an Application, instead of one by one, to save the user time, which is required for a particular process. There are many ways to upload multiple files in ASP.NET MVC, but in this article, we will use HttpPostedFileBase MVC class to upload the multiple files, instead of any script like jQuery or JavaScript. Lets start implementing this scenario, step by step with the help of a simple ASP.NET Application. Thus, the beginners and students can understand easily.
 
Step 1: Create an MVC Application.

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

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

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

    NEW

Step 2: Create Model Class

Now, let us create the model class, named FileModel.cs, by right clicking on Models folder, as shown in the screenshot, given below:
 
Create Model Class
 
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 the folder name or in a separate class library.
 
FileModel.cs class code snippet,
  1. using System.ComponentModel.DataAnnotations;  
  2. using System.Web;  
  3.   
  4. namespace UploadMultipleFilesInMVC.Models  
  5. {  
  6.     public class FileModel  
  7.     {  
  8.         [Required(ErrorMessage ="Please select file.")]  
  9.         [Display(Name ="Browse File")]  
  10.         public HttpPostedFileBase[] files { getset; }  
  11.          
  12.     }  

In the preceding code snippet, we are using HttpPostedFileBase, which is the easiest way to read the uploaded files and pass to the controller.
 
Step 3 : Add Controller Class

Now, let us add ASP.NET MVC controller, as shown in the screenshot, given below:
 
Add Controller Class
 
After clicking Add button, it will show the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller to upload the multiple files. After modifying the code of Homecontroller class, the code will look like:
 
HomeController.cs
  1. using System.IO;  
  2. using System.Linq;  
  3. using System.Web;  
  4. using System.Web.Mvc;  
  5.   
  6. namespace UploadMultipleFilesInMVC.Controllers  
  7. {  
  8.     public class HomeController : Controller  
  9.     {  
  10.         // GET: Home  
  11.         public ActionResult UploadFiles()  
  12.         {  
  13.             return View();  
  14.         }  
  15.         [HttpPost]  
  16.         public ActionResult UploadFiles(HttpPostedFileBase[] files)  
  17.         {  
  18.   
  19.             //Ensure model state is valid  
  20.             if (ModelState.IsValid)  
  21.             {   //iterating through multiple file collection   
  22.                 foreach (HttpPostedFileBase file in files)  
  23.                 {  
  24.                     //Checking file is available to save.  
  25.                     if (file != null)  
  26.                     {  
  27.                         var InputFileName = Path.GetFileName(file.FileName);  
  28.                         var ServerSavePath = Path.Combine(Server.MapPath("~/UploadedFiles/") + InputFileName);  
  29.                         //Save file to server folder  
  30.                         file.SaveAs(ServerSavePath);  
  31.                         //assigning file uploaded status to ViewBag for showing message to user.  
  32.                         ViewBag.UploadStatus = files.Count().ToString() + " files uploaded successfully.";  
  33.                     }  
  34.    
  35.                 }  
  36.             }  
  37.             return View();  
  38.         }  
  39.     }  

Step 4 : Creating strongly typed view
 
Right click on View folder of the created Application and choose add view, select FileModel class along with creating scaffolding template to create the strongly typed view to upload the multiple files as: 
 
Creating strongly typed view
Click Add button and it will create the view named UploadFiles. Now, open the UploadFiles.cshtml view, change the default code, as per requirement to upload the multiple files, which is generated by MVC scaffolding template as:

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

Right click on the created ASP.NET MVC Application, Solution Explorer and choose add new item, Add New Folder. After adding the model, view, controller and UploadedFiles folder, Solution explorer will look like:
 
Create a folder
 
Now, we have done all the coding to upload the files.

Step 6: Run the Application.
 
After running the application, click upload button without selecting the file. It will show the following error message, which is set in created FileModel class as:
 
 run the application
Now, browse the file from your machine hard disc location or any other storage device, which is connected to the machine and select one by one files by pressing a control key or if you want to select the multiple files, press Ctrl+A keys, as shown in the screenshot, given below:
 
UPLOAD
Now, after selecting the multiple files, click upload button and it will show the following message after uploading the files as:
 
upload
Now, let's ensure our uploaded files are uploaded to the Server folder by browsing the Server folder location, which is used to save the uploaded files. After browsing the Server folder, the uploaded files will be located as follows:
 
files
 
I hope from all the preceding examples and explanations  we have learned how to upload multiple files in ASP.NET MVC . 
 
Note
  • HttpPostedFileBase instance name must be a same as file uploader control name.
  • Its important to define enctype = "multipart/form-data" in form action, else the value will be null in the 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. Thus, improve it, depending on your skills.
Summary

I hope uploading multiple files in ASP.NET MVC article is useful for all the readers to upload the multiple files in ASP.NET MVC. If you have any suggestions, please contact me.

Read more articles on ASP.NET:


Similar Articles