Home > DeveloperSection > Forums > How to do File Uploading in ASP.NET MVC 3.0
Ashish Pandey

Total Post:128

Points:898
Posted on    November-21-2014 11:15 PM

 ASP.NET MVC C#  Mvc3  File  Upload 
Ratings:


 1 Reply(s)
 578  View(s)
Rate this:

I want to upload file in asp.net-mvc. How can I upload the file using html input file control?



Manoj Bhatt
Manoj Bhatt

Total Post:153

Points:1079
Posted on    November-22-2014 1:23 AM

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

{

    // This action renders the form

    public ActionResult Index()

    {

        return View();

    }

 

    // This action handles the form POST and the upload

    [HttpPost]

    public ActionResult Index(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 ~/App_Data/uploads folder

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

            file.SaveAs(path);

        }

        // redirect back to the index action to show the form once again

        return RedirectToAction("Index");       

    }

}


Don't want to miss updates? Please click the below button!

Follow MindStick