Thursday, 8 January 2015

File upload in MVC3/4

Those new to MVC or coming from classic ASP.NET might be a little daunted when first tasked with uploading a file in MVC , as there's no concept of the fileupload control (or any server side control for that matter)?

Thanks to Darin Dimitrov for the great example here:

Your controller

public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
return View();
}
// This action handles the form POST and the upload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
}


The view


@using (Html.BeginForm("Index""Home"FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />

<input type="submit" value="OK" />
}

No comments:

Post a Comment