Thursday, January 7, 2010

Uploading files using ASP.NET MVC 2

In ASP.NET MVC 1 you had to check the Request.Files property when you want to upload one or more files from your web application.

   1:  public class HomeController : Controller
   2:  {
   3:    public ActionResult ProcessFiles()
   4:    {
   5:      foreach (string file in Request.Files)
   6:      {
   7:            //Process files
   8:      }
   9:      return View();
  10:    }
  11:  }

As this is not directly helping to make a testable controller action, they were some initiatives to make this testable.

In ASP.NET MVC 2 you get by default a ModelBinder that extracts the files from the Request and assign it to a parameter of your controller action method.

   1:  public class HomeController : Controller
   2:  {
   3:    public ActionResult ProcessFiles(IEnumerable<HttpPostedFileBase> files)
   4:    {
   5:      foreach (var file in files)
   6:      {
   7:        //Process files
   8:      }
   9:      return View();
  10:    }
  11:  }

Beautiful isn’t it?

2 comments:

Anonymous said...

"In ASP.NET MVC 1 you had to check the Request.Files property when you want to upload" - sorry, but this is not true.

In ASP.NET MVC 1, if you define an action method like this:

public ActionResult UploadFile(HttpPostedFileBase uploadedFile)

And your HTML looks like this:

[form>
[input type="file" name="uploadedFile" />
[/form>

...then it gets bound properly by the DefaultModelBinder.

I'm not sure whether IEnumerable works, though.

Anonymous said...

Unfortunately, it doesn't seem to work and I'm using MVC 2. Maybe I'm doing something wrong.
Alas, the foreach in Request.Files work, as long as you don't forget to put: enctype="multipart/form-data" in your form