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.
Now, let us start with a step by step approach from the creation of a simple MVC Application in the following:
- "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
- 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:
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:
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,
using System.ComponentModel.DataAnnotations; using System.Web; namespace UploadMultipleFilesInMVC.Models { public class FileModel { [Required(ErrorMessage ="Please select file.")] [Display(Name ="Browse File")] public HttpPostedFileBase[] files { get; set; } } }
Step 3 : Add Controller Class
Now, let us add ASP.NET MVC controller, as shown in the screenshot, given below:
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
using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; namespace UploadMultipleFilesInMVC.Controllers { public class HomeController : Controller { // GET: Home public ActionResult UploadFiles() { return View(); } [HttpPost] public ActionResult UploadFiles(HttpPostedFileBase[] files) { //Ensure model state is valid if (ModelState.IsValid) { //iterating through multiple file collection foreach (HttpPostedFileBase file in files) { //Checking file is available to save. if (file != null) { var InputFileName = Path.GetFileName(file.FileName); var ServerSavePath = Path.Combine(Server.MapPath("~/UploadedFiles/") + InputFileName); //Save file to server folder file.SaveAs(ServerSavePath); //assigning file uploaded status to ViewBag for showing message to user. ViewBag.UploadStatus = files.Count().ToString() + " files uploaded successfully."; } } } return 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:
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
@model UploadMultipleFilesInMVC.Models.FileModel @{ ViewBag.Title = "www.compilemode.com"; } @using (Html.BeginForm("UploadFiles", "Home", 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.files, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" }) @Html.ValidationMessageFor(model => model.files, "", 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.UploadStatus </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>
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:
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:
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:
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:
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:
Read more articles on ASP.NET:
Post a Comment