Showing posts with label Upload Files in ASP.NET MVC. Show all posts
Showing posts with label Upload Files in ASP.NET MVC. Show all posts

Friday, September 25, 2015

Upload Files in ASP.NET MVC

<h2>Basic File Upload</h2>
@using (Html.BeginForm("Index",
                        "Home",
                        FormMethod.Post,
                        new { enctype = "multipart/form-data" }))
{
    <label for="file">Upload Image:</label>
    <input type="file" name="file" id="file" /><br><br>
    <input type="submit" value="Upload Image" />
    <br><br>
    @ViewBag.Message
}

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
                try
                {
                    string path = Path.Combine(Server.MapPath("~/Images"),
                                               Path.GetFileName(file.FileName));
                    file.SaveAs(path);
                    ViewBag.Message = "File uploaded successfully";
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            else
            {
                ViewBag.Message = "You have not specified a file.";
            }
            return View();

        }