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:

Controller:

public class SampleController : Controller {

    public ActionResult Index() {
        return View();
    }

    [ActionName("Index")]
    [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
            if(!System.IO.Directory.Exists(Server.MapPath("~/Content/PostedFiles")))
                System.IO.Directory.CreateDirectory(
                    Server.MapPath("~/Content/PostedFiles")
                );

            //Set the full path
            string path = System.IO.Path.Combine(
                Server.MapPath("~/Content/PostedFiles"),
                System.IO.Path.GetFileName(File.FileName)
            );

            //Save the thing
            File.SaveAs(path);

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

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

}

View:

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

@if (TempData["Result"] != null) { 
    <ul>
        <li>@TempData["Result"]</li>
    </ul>
}

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

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.