Uploading files with ASP.NET MVC

For those who want to upload files using ASP.NET MVC will find that the process and objects you used in ASP.NET WebForms has changed slightly for ASP.NET MVC.

MVC uses a HttpPostedFileBase object rather than the HttpPostedFile object that you may be used to.

This is the code I used recently to enable file uploading in my MVC app.

In the View:

<form action="/home/Import" method="post" enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />

and in the Controller:

public ActionResult Import(FormCollection form)
    foreach (string file in Request.Files)
        HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
        if (hpf.ContentLength != 0)
            StreamReader sr = new StreamReader(hpf.InputStream);
            //Do Something with Stream
            return View("ImportFailed");
    return View("ImportSucceeded");

Leave a Reply