Recently I got a chance to work on an MVC Project, In Which had a requirement to implement upload and download functionality in my Web application. Now I decided to write an article on this topic so that it will help others developer also who is looking for the same.
Now I have Created an Empty MVC application and also Created a folder “PdfFiles” in my project where we need to save the uploaded pdf files.
- Now Add a controller “Home” in the Project and also add an action method in it.
- Right Click in the Action Method and add a View
View Html Code
@model IEnumerable<WebAppMvc.Controllers.FilesInoformation>
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("UploadPdf", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<fieldset>
<legend>Upload a Pdf file</legend>
<div class="editor-field">
@Html.TextBox("file", "", new { type = "file", accept = "application/pdf" })
</div>
<br />
<br />
<div class="editor-field">
<input type="submit" value="Upload Pdf" />
</div>
<div class="row">
<h3>Uploaded Filles</h3>
<table class="table">
<thead>
<tr>
<th>FileName</th>
<th>Action</th>
</tr>
</thead>
@if (Model != null)
{
foreach (var file in Model)
{
<tr>
<td>@file.filename</td>
<td><a href="@Url.Action("", "",new {filename=file.filename })">Download</a></td>
</tr>
}
}
</table>
</div>
</fieldset>
}
Controller Code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebAppMvc.Controllers
{
public class FilesInoformation
{
public string filename { get; set; }
}
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
//getting the list of file uploaded
DirectoryInfo directory = new DirectoryInfo(Server.MapPath(@"~\PdfFiles"));
var files = directory.GetFiles().ToList();
List<FilesInoformation> model = new List<FilesInoformation>();
foreach (var file in files)
{
model.Add(new FilesInoformation { filename = file.Name });
}
return View(model);
}
[HttpPost]
public ActionResult UploadPdf(HttpPostedFileBase file)
{
//action method for uploading the pdf file
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var Pdfpath = Path.Combine(Server.MapPath("~/PdfFiles"), fileName);
file.SaveAs(Pdfpath);
}
}
catch
{
}
return RedirectToAction("Index");
}
public FileResult DownloadPdf(string filename)
{
//action method for downloadig the pdf file
string filepath = Server.MapPath(@"~\PdfFiles\")+ filename;
return File(filepath, "application/force-", filename);
}
}
}
Add comment