Hi friends, in this article I will explain about how the FileUpload control works with
MVC3, how to upload a file and how to delete an uploaded file.
In previos article I already explained about How to use Datepicker Calender Control In Asp.Net Mvc Application || How to Use jQuery Calender In MVC3.,How to pass or send List from Controller to View and Binding and Sorting Grid in ASP.NET MVC using Jquery
Model: FileModel.csIn previos article I already explained about How to use Datepicker Calender Control In Asp.Net Mvc Application || How to Use jQuery Calender In MVC3.,How to pass or send List from Controller to View and Binding and Sorting Grid in ASP.NET MVC using Jquery
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
@model MvcFileUpload.Models.FileModel
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function
() {
if ('@ViewBag.Message' == 'File Uploaded
Successfully') {
alert('File
Uploaded Successfully');
}
if ('@ViewBag.Message' == 'File is already
exists') {
alert('File
is already exists');
}
$('#imgDelete').click(function () {
var
filename = $(this).parent().parent().parent().attr('id');
$(this).parent().parent().parent().remove();
$.ajax({
type: "post",
url: "/File/RemoveUploadFile?fileName="
+ filename,
datatype: "json",
traditional: true,
success: function (data) {
alert('File Deleted Successfully');
if
(data == 0) {
$('#tbl_FileUpload').remove();
}
}
});
});
});
</script>
@{
ViewBag.Title = "File
Upload";
}
<h2>
File Upload Page</h2>
@using (@Html.BeginForm("FileUpload",
"File", FormMethod.Post, new { @id = "form1",
@enctype = "multipart/form-data" }))
{
<table>
<tr>
<td>
<input type="file" name="file_Uploader" />
</td>
<td>
<input type="submit" id="btn_Upload" value="Upload" />
</td>
</tr>
</table>
if
(Session["Uploadedfile"] != null)
{
<table id="tbl_FileUpload" border="1">
<thead>
<tr>
<th>
Uploaded File Name
</th>
<th>
Delete
</th>
</tr>
</thead>
<tbody>
@foreach (var item in
(List<MvcFileUpload.Models.FileModel>)Session["Uploadedfile"])
{
<tr id="@item.FileName">
<td>@item.FileName
</td>
<td style="text-align: center">
<a class="viewc" href="">
<img src="../../Images/delete.png"
width="25"
height="25"
class="link"
alt="delete"
id="imgDelete"/>
</a>
</td>
</tr>
}
</tbody>
</table>
}
}
|
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);
}
}
}
|
The output of the above code as shown in the below figure.
When we upload the file,then table will be displayed with Uploaded file name and Delete.When we click on delete button then file will be deleted with alert of "file deleted successfully".
You can download the code by clicking on the below Download image.
No comments:
Post a Comment