Creating a multiple file upload form in ASP.NET MVC

Posted by ben 13. November 2010 21:36

I’ve been testing out ASP.NET MVC 3 RC this week and am really enjoying working with the new razor syntax.

This post demonstrates how using the Microsoft Web Helpers library, you can create a multiple file upload form.

First thing is to add the Microsoft Web Helpers package (I’m assuming you have MVC 3 RC installed and can therefore use NuGet).

In solution explorer right click your project and select “Add Library Package Reference”. Search for “Web Helpers” and install the package:

image

So that you can reference the helpers from your Razor views, you will want to add the namespace to web.config (yes this is now possible with Razor). See the solution here).

Add the namespace “Microsoft.Web.Helpers”.

Next lets add our controller get and post actions:

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

        [HttpPost]
        public ActionResult Upload(IEnumerable<HttpPostedFileBase> fileUpload)
        {
            foreach (var file in fileUpload)
            {
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    file.SaveAs(path);
                }
            }
            return RedirectToAction("Index");
        }

As you can see, the post action method expects an IEnumerable<HttpPostFileBase>. This is created by the model binder, by looking for file input controls on the form, named “fileUpload” (this is the name used by the FileUpload helper).

Let’s add our view:

<h2>Upload</h2>

@FileUpload.GetHtml(5, uploadText: "Upload files")

That’s all you need! All the parameters are optional. Here I am setting the initial number of upload inputs to display and the text of the upload button.

Gotta love MVC!

Tags:
Categories ASP.NET

blog comments powered by Disqus