HOW TO FILE UPLOAD IN MVC?

marcel ethan

Total Post:105

Points:735
Posted by  marcel ethan
 897  View(s)
Ratings:
Rate this:
How can I upload the file using html input file control
  1. Kamlakar Singh

    Post:194

    Points:1396
    Re: How to file upload in mvc?

    You don't use a file input control. Server side controls are not used in ASP.NET MVC.

    So you would start by creating an HTML form which would contain a file input.

     @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))

    {

        <input type="file" name="file" />

        <input type="submit" value="OK" />

    }

    and then you would have a controller to handle the upload.

    public class HomeController : Controller

            {

                public ActionResult Index()

                {

                    return View();

                }

     

                [HttpPost]

                public ActionResult Index(HttpPostedFileBase file)

                {

                    if (file != null && file.ContentLength > 0)

                    {

                        var fileName = Path.GetFileName(file.FileName);

                        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);

                        file.SaveAs(path);

                    }

                    return RedirectToAction("Index");

                }

            }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!