File Upload in MVC 4

Note: Assuming that the user has Basic Knowledge of MVC 4
 
1. Create an MVC Project - MvcPractice.

2. Add an empty Controller, Name it as UploadController.
 
Controller Code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.IO;  
  7. namespace MvcPractice1.Controllers {  
  8.     public class UploadController: Controller {  
  9.         public ActionResult Index() {  
  10.             return View();  
  11.         }  
  12.         public ActionResult file() {  
  13.                 return View();  
  14.             }  
  15.             [HttpPost]  
  16.         public ActionResult file(HttpPostedFileBase file) {  
  17.             if (file != null && file.ContentLength > 0)  
  18.                 try {  
  19.                     string path = Path.Combine(Server.MapPath("~/Content/Files"),  
  20.                         Path.GetFileName(file.FileName));  
  21.                     file.SaveAs(path);  
  22.                     ViewBag.Message = "File uploaded successfully";  
  23.                 } catch (Exception ex) {  
  24.                 ViewBag.Message = "ERROR:" + ex.Message.ToString();  
  25.             } else {  
  26.                 ViewBag.Message = "You have not specified a file.";  
  27.             }  
  28.             return View();  
  29.         }  
  30.     }  

After writing the entire controller code, right click in the action --- public ActionResult file() and create a view - "file".
 
Code for file.cshtml 
  1. <h2>file</h2>  
  2. <h2>Upload file</h2> @using (Html.BeginForm ("file""upload", FormMethod.Post, new { enctype = "multipart/form-data" })) {  
  3.    <input type="file" name="file" id="file" />  
  4.    <br>  
  5.    <br>  
  6.       <input type="submit" value="Upload file" />  
  7.    <br>  
  8.    <br>
  9. }
 Note : Include a file named Files in the Content folder in the root directory(ie, your project location)