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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.IO;
- namespace MvcPractice1.Controllers {
- public class UploadController: Controller {
- public ActionResult Index() {
- return View();
- }
- public ActionResult file() {
- return View();
- }
- [HttpPost]
- public ActionResult file(HttpPostedFileBase file) {
- if (file != null && file.ContentLength > 0)
- try {
- string path = Path.Combine(Server.MapPath("~/Content/Files"),
- Path.GetFileName(file.FileName));
- file.SaveAs(path);
- ViewBag.Message = "File uploaded successfully";
- } catch (Exception ex) {
- ViewBag.Message = "ERROR:" + ex.Message.ToString();
- } else {
- ViewBag.Message = "You have not specified a file.";
- }
- return View();
- }
- }
- }
After writing the entire controller code, right click in the action --- public ActionResult file() and create a view - "file".
Code for file.cshtml
- <h2>file</h2>
- <h2>Upload file</h2> @using (Html.BeginForm ("file", "upload", FormMethod.Post, new { enctype = "multipart/form-data" })) {
- <input type="file" name="file" id="file" />
- <br>
- <br>
- <input type="submit" value="Upload file" />
- <br>
- <br>
- }
Note : Include a file named Files in the Content folder in the root directory(ie, your project location)