Multi fileupload in MVC 5 & Razor


In this post we will learn how to upload multiple files at a time using multi fileupload in MVC 5 & razor

Add one controller and write the following code in it

Action Method
//
// GET: /Multi Fileupload/
//
public ActionResult Index()
{
return View();
}
//
// POST: /Multi Fileupload/
//
[HttpPost]
public ActionResult Index(ICollection<HttpPostedFileBase> fu_files)
{
var directory = Server.MapPath(“~/Content/Uploads/”);
foreach (HttpPostedFileBase file in fu_files)
{
if (file != null && file.ContentLength > 0)
{
Stream fs = file.InputStream;
int size = file.ContentLength;
byte[] bytes = new byte[size];
fs.Read(bytes, 0, size);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
System.IO.File.WriteAllBytes(directory + file.FileName, bytes);
}
}
Dictionary<string, string> UploadedImages = new Dictionary<string, string>();
foreach (var item in Directory.EnumerateFileSystemEntries(directory))
{
string[] str = item.Split(new char[] { ‘\\’ }, StringSplitOptions.RemoveEmptyEntries);
UploadedImages.Add(str[str.Length – 1], “/Content/Uploads/” + str[str.Length – 1]);
}
ViewBag.UploadedImages = UploadedImages;
return View();
}

Then add the view and write the following code

View
@{
ViewBag.Title = “Multi Fileupload in MVC || Chikkanti.wordpress.com”;
}<h2>Multi Fileupload in MVC</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = “multipart/form-data” }))
{
<table border=”1″ style=”border-color:black;background:#f5c9c9″>
<tr>
<td>
<input type=”file” name=”fu_files” multiple />
</td>
<td>
<input type=”submit” id=”resume” name=”name” value=”Submit” />
</td>
</tr>
@if (ViewBag.UploadedImages != null)
{
<tr>
<td><strong>Name</strong></td>
<td><strong>Image</strong></td>
</tr>
Dictionary<string, string> Images = ViewBag.UploadedImages as Dictionary<string, string>;
foreach (var Image in Images.Keys)
{
<tr>
<td>@Image</td>
<td><img src=’@Images[Image] height=”100px” width=”100px” /></td>
</tr>
}
}
else
{
<tr>
<td colspan=”2″><span>No files uploaded.</span></td>
</tr>
}
</table>
}

Rebuild the application and run

image

image

image

image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s