Sunday, June 23, 2013

Upload a File in ASP.NET MVC


View:

@using (Html.BeginForm("ImageUpload", "Item", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmUp" }))
 {
     <input type="file" name="file" /><br />
     <div align="left">
     <input type="submit" value="Upload" />
     </div>
   }

Item is your controller name and ImageUpload is your action name.

Controller:

 [HttpPost]
        public ActionResult ImageUpload(HttpPostedFileBase file)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/Images folder
                var path = Path.Combine("/Images/", fileName);
                file.SaveAs(Server.MapPath(path));
            }
            // redirect back to the index action to show the form once again
            return RedirectToAction("Index");
           
        }

No comments:
Write comments
Recommended Posts × +