23 February 2011 ASP.NET MVC, fileupload CI Team

imageIn this HowTo I´m going to give you a short invitation how to implement a fileupload with ASP.NET MVC.

The Controller

On the controller-side we create an ActionMethod named "FileUpload":

        public ActionResult FileUpload(HttpPostedFileBase file)
            ViewData["Message"] = file.FileName + " - " + file.ContentLength.ToString();
            return View("Index");

HttpPostedFileBase is an abstract basic-class and has the same characteristics like HttpPostedFile. That´s because you are able to make this with a UnitTest as well and create your own deductions from the abstract basic-class.

With "file" I´m able to reach several characteristics with this method and if I want to I can save the file:


Now the Frontend:

The View

In the "index" view I create a formulary with the HTML Helper.

Important: The fileupload only works when enctype="multipart/form-data" is activated!

                               new {enctype = "multipart/form-data"})) { %>
        <input type="file" name="file" id="file" />
        <input type="submit" name="submit" value="Submit" />
        <% } %>

Simple and fast Smiley 

File size:

Usually you won´t be able to upload files with more than 4MB. But you can change this in the web.config: maxRequestSize

More Information´s

Scott Hanselman has written a fantastic Blogpost about this subject. It also includes how Unit-Tests could look like in such a case.

[Download Democode]