Friday, November 12, 2010

FileUploader in asp.net MVC2

as we all know ASP.NET MVC sits on top of ASP.NET. That means ASP.NET MVC didn't do any special work for File Upload support. It uses whatever stuff is built into ASP.NET itself.

So the core process is still same for file upload:
below is code for view

Code for how to Upload file in ASP.NET MVC2



< %@ Page Title="" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" % >

< asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server" >
FileUpload
< /asp:Content >
< asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server" >
< h2 >FileUpload< /h2 >

< % using (Html.BeginForm("FileUpload", "FileUpload",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{% >
< input name="uploadFile" type="file" / >
< input type="submit" value="Upload File" / >
< %} % >

< /asp:Content >


//and this is code for controller class:
[HandleError]
public class FileUploadController : Controller
{
public ActionResult FileUpload()
{
return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
}

How to Upload file in ASP.NET MVC2 by Rajesh Rolen

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates