MVC : File Upload in ASP.Net MVC application || How to Upload and delete Uploaded file in MVC
This article explains how the FileUpload control works with MVC, how to upload a file and how to delete an uploaded file.
Model: FileModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcFileUpload.Models
{
public class FileModel
{
public string FileName { get; set; }
public string FilePath { get; set; }
}
}
Controller: FileController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcFileUpload.Models;
using System.IO;
namespace MvcFileUpload.Controllers
{
public class FileController : Controller
{
public ActionResult FileUpload()
{
return View();
}
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file_Uploader)
{
if (file_Uploader != null)
{
string fileName = string.Empty;
string destinationPath = string.Empty;
List<FileModel> uploadFileModel = new List<FileModel>();
fileName = Path.GetFileName(file_Uploader.FileName);
destinationPath = Path.Combine(Server.MapPath("~/UploadFiles/"), fileName);
file_Uploader.SaveAs(destinationPath);
if (Session["Uploadedfile"] != null)
{
var isFileNameRepete = ((List<FileModel>)Session["Uploadedfile"]).Find(x => x.FileName == fileName);
if (isFileNameRepete == null)
{
uploadFileModel.Add(new FileModel { FileName = fileName, FilePath = destinationPath });
((List<FileModel>)Session["Uploadedfile"]).Add(new FileModel { FileName = fileName, FilePath = destinationPath });
ViewBag.Message = "File Uploaded Successfully";
}
else
{
ViewBag.Message = "File is already exists";
}
}
else
{
uploadFileModel.Add(new FileModel { FileName = fileName, FilePath = destinationPath });
Session["Uploadedfile"] = uploadFileModel;
ViewBag.Message = "File Uploaded Successfully";
}
}
return View();
}
[HttpPost]
public ActionResult RemoveUploadFile(string fileName)
{
int sessionFileCount = 0;
try
{
if (Session["Uploadedfile"] != null)
{
((List<FileModel>)Session["Uploadedfile"]).RemoveAll(x => x.FileName == fileName);
sessionFileCount = ((List<FileModel>)Session["Uploadedfile"]).Count;
if (fileName != null || fileName != string.Empty)
{
FileInfo file = new FileInfo(Server.MapPath("~/UploadFiles/" + fileName));
if (file.Exists)
{
file.Delete();
}
}
}
if (sessionFileCount == 0)
{
Session["Uploadedfile"] = null;
}
}
catch (Exception ex)
{
throw ex;
}
return Json(sessionFileCount, JsonRequestBehavior.AllowGet);
}
}
}
View: FileUpload.cshtml
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcFileUpload.Models;
using System.IO;
namespace MvcFileUpload.Controllers
{
public class FileController : Controller
{
public ActionResult FileUpload()
{
return View();
}
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file_Uploader)
{
if (file_Uploader != null)
{
string fileName = string.Empty;
string destinationPath = string.Empty;
List<FileModel> uploadFileModel = new List<FileModel>();
fileName = Path.GetFileName(file_Uploader.FileName);
destinationPath = Path.Combine(Server.MapPath("~/UploadFiles/"), fileName);
file_Uploader.SaveAs(destinationPath);
if (Session["Uploadedfile"] != null)
{
var isFileNameRepete = ((List<FileModel>)Session["Uploadedfile"]).Find(x => x.FileName == fileName);
if (isFileNameRepete == null)
{
uploadFileModel.Add(new FileModel { FileName = fileName, FilePath = destinationPath });
((List<FileModel>)Session["Uploadedfile"]).Add(new FileModel { FileName = fileName, FilePath = destinationPath });
ViewBag.Message = "File Uploaded Successfully";
}
else
{
ViewBag.Message = "File is already exists";
}
}
else
{
uploadFileModel.Add(new FileModel { FileName = fileName, FilePath = destinationPath });
Session["Uploadedfile"] = uploadFileModel;
ViewBag.Message = "File Uploaded Successfully";
}
}
return View();
}
[HttpPost]
public ActionResult RemoveUploadFile(string fileName)
{
int sessionFileCount = 0;
try
{
if (Session["Uploadedfile"] != null)
{
((List<FileModel>)Session["Uploadedfile"]).RemoveAll(x => x.FileName == fileName);
sessionFileCount = ((List<FileModel>)Session["Uploadedfile"]).Count;
if (fileName != null || fileName != string.Empty)
{
FileInfo file = new FileInfo(Server.MapPath("~/UploadFiles/" + fileName));
if (file.Exists)
{
file.Delete();
}
}
}
if (sessionFileCount == 0)
{
Session["Uploadedfile"] = null;
}
}
catch (Exception ex)
{
throw ex;
}
return Json(sessionFileCount, JsonRequestBehavior.AllowGet);
}
}
}
Routing: Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcFileUpload
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "File", action = "FileUpload", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
Output