Sunday, December 19, 2010

How to upload file in MVC ASP.NET

In view (.aspx):

<form action="/Home/SaveDocuments" method="post" enctype="multipart/form-data">
    <label for="file1">Upload Documents</label>
    <input type="file" id="file1" name="file1" class="multi"/>
    <input type="submit" value="Upload" />
</form>

In Controller:

        public string EventFileDirectory = @"C:\Downloads";
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SaveDocuments()
        {
            foreach (string inputTagName in Request.Files)
            {
                System.Web.HttpPostedFileBase file = Request.Files[inputTagName];
                if (file.ContentLength > 0)
                {
                    string filePath = System.IO.Path.Combine(EventFileDirectory, System.IO.Path.GetFileName(file.FileName));
                    file.SaveAs(filePath);
                }
            }
            return RedirectToAction("Index", "Home");
        }