ASP.NET MVC File Upload

This very short blog post will show you how to add support for uploading files to an ASP.NET MVC application.

Add a controller action

Add a controller action that accepts a parameter of type HttpPostedFileBase. In the example below, I save the file to my App_Data folder. I would highly recommend that you redirect the browser to another action when done.

public ActionResult Upload(HttpPostedFileBase file)
{
    var fileName = Path.Combine(Request.MapPath("~/App_Data"), Path.GetFileName(file.FileName));
    file.SaveAs(fileName);
    return RedirectToAction("Index");
}

Add an upload form

Add an upload form. Set the action to your upload controller action, the method to post, and very important, the enctype to multipart/form-data.

<form action="/Home/Upload" method="post" enctype="multipart/form-data">
    <label>Filename: <input type="file" name="file" /></label>
    <input type="submit" value="Submit" />
</form>

You’re done

That is all that is needed. Compile your app and give it a try. You browse or checkout the full source code from my googlecode repository.

Comments

#1 Kampanye Damai Pemilu Indonesia 2009 on Wednesday, April 29 2009 at 6:19 AM

thanks for this usefull informations.. now i find what i want to know.. thanks a lot..

#2 friendster graphics on Thursday, May 07 2009 at 2:21 AM

i feel lucky now..

now i find something that i want to kinow.. thank you..