ASP.NET MVC Code Review #1 - File Upload With HttpPostedFileBase Class

This is #1 of the series of blog posts which is about some core scenarios on ASP.NET MVC: File Upload With HttpPostedFileBase Class
29 December 2011
2 minutes read

Related Posts

Today, I decided to change my blogging style a little bit. I always try to write posts which contains detailed information about the subject but I realized that it prevents me from writing much more useful things. So, from now on, I will drop a bunch of code on the screen and talk about that briefly.

This is the beginning of the series of blog posts which is about some core scenarios on ASP.NET MVC. In this one, code review #1, I will give you an example on how to get file upload functionality working in ASP.NET MVC. Here is the code:


public class SampleController : Controller {

    public ActionResult Index() {
        return View();

    [ValidateAntiForgeryToken, HttpPost]
    public ActionResult Index_post(HttpPostedFileBase File) {

        //Check if the file is not null and content length is bigger than 0
        if (File != null && File.ContentLength > 0) {

            //Check if folder is there

            //Set the full path
            string path = System.IO.Path.Combine(

            //Save the thing

            TempData["Result"] = "File created successfully!";

        //RedirectToAction so that we can get rid of so-called "Form Resubmission"
        return RedirectToAction("Index");



    ViewBag.Title = "File Upload Sample";
<h2>File Upload Sample</h2>

@if (TempData["Result"] != null) { 

@using (Html.BeginForm("index", "sample", 
    FormMethod.Post, new { enctype = "multipart/form-data" })) {
    <input type="file" name="File" />
        <input type="submit" value="Upload" />

Actually, code explains itself nicely here but I see one thing to worth pointing out here. HttpPostedFileBaseModelBinder class from System.Web.Mvc namespace is the class which binds a model to a posted file. So, the parameter (which is type of HttpPostedFileBase) of the Index_post method receives the posted file.

Pretty neat stuff. Hope you enjoy it.