Home > DeveloperSection > Beginner > FileUpload in ASP.NET MVC

FileUpload in ASP.NET MVC


ASP.NET MVC ASP.NET MVC 
Ratings:
0 Comment(s)
 6042  View(s)
Rate this:

FileUpload in ASP.NET MVC

In this I article I will explain how to upload file from the client computer to the server.

Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project as seen below:

FileUpload in ASP.NET MVC

Choose Razor as the view engine and click OK.

FileUpload in ASP.NET MVC

Add a controller in your project and give name as HomeController as shown in the below figure:

FileUpload in ASP.NET MVC

Add a view (Index) and create a file upload control with the help of HTML as shown below:

<html>

<head>

    <title>Index</title>

</head>

<body>

    <div>

        <h2>Upload File</h2>

        <form  method="post" enctype="multipart/form-data">

            <label>Filename: <input type="file" name="file" /></label>

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

        </form>

    </div>

</body>

</html>

 

After adding a control in view adds the following code in the controller to upload the file on the server:

using System.Web.Mvc;

using System.IO;

using System.Web;

 

namespace FileUploadDemo.Controllers

{

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult Index(HttpPostedFileBase file)

        {

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

            if (fileName != null)

                file.SaveAs(Server.MapPath("~\\files\\" + fileName));

            return View();

        }

    }

}

 

Run this application , you will see the following screen:

FileUpload in ASP.NET MVC

Thanks for reading this article, I think this will help you a lot.


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

Follow MindStick