1. Creating MVC Application
Let us implement these in a sample Application. Open Visual Studio. Go to File->New->Project. Give a suitable name to the Application. Click OK.
Select MVC Template. Click OK.
2. Adding Folder
We will add a folder to store the files in the application. Here, I have added a folder to the application.
3. Adding Controller
Let us add a controller. Right-click on the Controller. Add->Controller.
Select MVC 5 Controller -Empty. Click Add.
Give a suitable name to the controller.
Write the following code in the controller.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FileUpload.Controllers
{
public class UploadController: Controller
{
// GET: Upload
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult UploadFile()
{
return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0)
{
string _FileName = Path.GetFileName(file.FileName);
string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
file.SaveAs(_path);
}
ViewBag.Message = "File Uploaded Successfully!!";
return View();
}
catch
{
ViewBag.Message = "File upload failed!!";
return View();
}
}
}
}
4. Adding View
Right-click on UploadFileActionResult. Go to Add View.
Select the empty template. Click add.
Write the following code in the View.
@{
ViewBag.Title = "UploadFile";
}
<h2>UploadFile</h2>
@using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new { enctype="multipart/form-data"}))
{
<div>
@Html.TextBox("file", "", new { type= "file"}) <br />
<input type="submit" value="Upload" />
@ViewBag.Message
</div>
}
5. Browse the Application
Let us now run the Application and check if it is working fine or not. Browse the Application.
Click upload. I have debugged the code to verify that the file gets uploaded successfully.
The code is working as per the expectations, as it hits the success message. We should get this message on the View, as well.
We will verify the file uploaded by opening the folder in the Application’s directory.
Summary
Hence, we have just learned how to upload the file in ASP.NET MVC. I hope this post is useful to developers.