articles

Home / DeveloperSection / Articles / FileUpload in ASP.NET MVC

FileUpload in ASP.NET MVC

Chris Anderson9932 10-Oct-2011

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.


Updated 04-Mar-2020
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By