Doing File Upload in ASP .Net MVC 3 is easier than ASP .Net Web Form. On this example Only two controller and one view is needed to perform this task.
Controller
public class FileController : Controller
{
//
// GET: /File/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase f)
{
if (f.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath(“\\Uploads\\”), Path.GetFileName(f.FileName));
f.SaveAs(filePath);
}
return RedirectToAction(“Index”);
}
}
View
@{
ViewBag.Title = “Index”;
}
<h2>Index</h2>
@using (Html.BeginForm(“Upload”, “File”, FormMethod.Post, new { enctype = “multipart/form-data” }))
{
@Html.ValidationSummary(true)
<input type=”file” name=”f” /><br />
<input type=”submit” value=”Submit” />
}
Thats it.
Download the source Here
public class FileController : Controller { // // GET: /File/
public ActionResult Index() { return View(); } [HttpPost] public ActionResult Upload(HttpPostedFileBase f) { if (f.ContentLength > 0) { string filePath = Path.Combine(HttpContext.Server.MapPath(“\\Uploads\\”), Path.GetFileName(f.FileName)); f.SaveAs(filePath); } return RedirectToAction(“Index”); }
}