Site icon ParallelCodes

ASP.NET MVC Upload Multiple Files using HttpPostedFileBase

ASP.NET MVC Uploading multiple Files using HttpPostedFileBase example:

Often in a web project we have to integrate file upload control which can accept multiple files from the users and save it on the server side. In this example, we will see how to upload multiple files using HttpPostedFileBase in ASP.NET MVC project. Example shows a simple web page with one file input control which is being passed to the controller method and files are copied to a specified server folder location.

Create a new controller in your MVC project with name DefaultController.cs and edit it as below:

DefaultController.cs:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace MVCWebApp.Controllers
{
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult Index(List<HttpPostedFileBase> files)
{
try
{
if (files == null || files.Count == 0 || files[0] == null)
ViewBag.message = "Please select files to upload";
else
{
StringBuilder sbFiles = new StringBuilder();
sbFiles.Append("Uploaded Files:");
foreach(var file in files)
{
if (file != null)
{
string fileName = "file-" + Guid.NewGuid() + "-" + DateTime.Now.ToString("ddMMyyyyHHmmss") + Path.GetExtension(file.FileName);
string filePath = Path.Combine(Server.MapPath("~/UploadedFiles/") + fileName);
file.SaveAs(filePath);
sbFiles.Append("<br/><a href='/UploadedFiles/" + fileName + "' target='_blank'>" + fileName + "</a>");
}
}
ViewBag.message = sbFiles.ToString();
}
}
catch(Exception ex)
{
ViewBag.message = "Error occurred. Error:" + ex.Message.ToString();
}
return View();
}
}
}

The [HttpPost] Index method accepts a List<HttpPostedFileBase> which we are using to get the file information posted from the View. In this method, we are first checking for files object is valid or not. The if condition for checking files == null || files.Count == 0 || files[0] == null will ensure that the files object is not null and it contains files to be uploaded. Without this validation our code can run into run-time exceptions. The try catch block will ensure exception is caught if it occurs and will send appropriate error message using a ViewBag to our View.

Here StringBuilder - sbFiles object is being used to store file names which are being uploaded. Using forEach loop we are parsing files one-by-one and giving them a new name using system GUID, DateTime and file’s extension. All the files will be uploaded to “UploadedFiles” folder, so please create one folder with name “UploadedFiles” inside your project’s directory. file.SaveAs(filePath) will save our file to the file path location specified. Then we are appending a HTML anchor tag to display uploaded file names to the user.

Create a View for Index() method and edit it as below:

Index.cshtml:

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body style="font-family:Arial, Helvetica, sans-serif; font-size:18px;">
<div>
<br/>
<h3>ASP.NET MVC Multiple Files uploading example:</h3>
@using (Html.BeginForm("Index", "Default", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td>
Select Files to upload:
</td>
<td>
<input type="file" name="files" multiple/>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Upload Files to server"/>
</td>
</tr>
</table>
<p>
@Html.Raw(ViewBag.message)
</p>
}
</div>
</body>
</html>

HTML5 supports input file control with multiple property. This code will work in all browsers as nearly all browser supports HTML5 now a days. Please ensure the name of your input file control matches with the one passed in the HttpPost Controller method.

Output:

Download Source Code

Also see:

ASP.NET MVC JQuery AJAX Call to Controller HttpGet and HttpPost

ASP.NET MVC Razor Display HTML String from Model

ASP.NET MVC Show Notifications using JQuery

ASP.NET MVC – Convert Model to JSON in Javascript

ASP.NET MVC – How to use JQuery Datatable on Webforms

ASP.NET MVC – Using JQuery Datepicker

 


1
Exit mobile version