You are at correct place to give a good start on ASP.NET MVC. Here i am going to show you how to upload multiple files in asp.net mvc.here we go.
Design code in view:
@*Welcome to asp.net mvc tutorial about uploading images*@
@*Now we are in Views/Home/index.cshtml*@
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<h3>Upload Image</h3>
<input multiple type="file" name="files" value="Browse"/>
<br />
<input type="submit" value="Upload" />
}
@if(ViewBag.UploadSuccess==true)
{
<span>Upload Completed Successfully</span>
}
Controller code in HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ASPtutorial.Models; //your projectName.Models
using System.IO;
namespace ASPtutorial.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost] //must be post method
public ActionResult Index(List<HttpPostedFileBase> files) //take files as a list
{
var path = ""; //for path to save
foreach(var item in files) //iterate in each file
{
if (item != null) //check file is null or not
{
if (item.ContentLength > 0) //check length of bytes are greater then zero or not
{
//for checking uploaded file is image or not
if (Path.GetExtension(item.FileName).ToLower() == ".jpg"
|| Path.GetExtension(item.FileName).ToLower() == ".png"
|| Path.GetExtension(item.FileName).ToLower() == ".gif"
|| Path.GetExtension(item.FileName).ToLower() == ".jpeg")
{
path = Path.Combine(Server.MapPath("~/Content/Images"), item.FileName);
item.SaveAs(path);
ViewBag.UploadSuccess = true;
}
}
}
}
return View();
}
}
}
That's it for multiple file upload , if you wanna see the code in video the watch this,Ok Good luck :)
No comments:
Post a Comment