Sometimes we need reporting module in a project where the user or admin can upload and download the particular types of files with limitations.
Recently I got a chance to work on these types of modules, basically, I’m working in the admin module in which needs to allow the user to upload and download the pdf files.
So I decided to focus this article specifically on beginners and those who only want to upload PDF files and download files in table view using Mvc Ajax call. we will also discuss how we can upload multiple pdf files using Ajax in MVC.
Now let us start to create an MVC application to upload and download PDF files step-by-step.Let’s start with creating an empty MVC Project.Open your visual studion and add a simple Mvc project.
I have also created a folder for storing the uplaoded pdf files on server.

FileUploadController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace UploadingFileMvc.Controllers
{
public class FilesInoformation
{
public string filename { get; set; }
public string filepath { get; set; }
}
public class FileUploadController : Controller
{
// GET: FileUpload
// 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, filepath = "/PdfFiles/" + file.Name });
}
return View(model);
}
[HttpPost]
public ActionResult UploadPdfFiles()
{
// Checking if Request object has file
if (Request.Files.Count > 0)
{
try
{
HttpPostedFileBase file = Request.Files[0];
string fname = file.FileName;
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/PdfFiles/"), fname);
file.SaveAs(fname);
return Json("Pdf Uplaoded Successfully!");
}
catch (Exception ex)
{
return Json(ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
}
}
View Html Code
Uploading a pdf file in the Asp.Net MVC application is a very simple and quick task, we can easily achieve this task. The posted pdf file is automatically available as a HttpPostedFileBase parameter in the action method of the controller.
For uploading a pdf file on the server you are required to have a file input control within HTML form with encoding type set to multipart/form-data.
@model IEnumerable<UploadingFileMvc.Controllers.FilesInoformation>
@{
ViewBag.Title = "";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
@using (Html.BeginForm("UploadPdf", "FileUpload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<fieldset>
<legend>Upload a Pdf file By Ajax</legend>
<div class="editor-field">
@Html.TextBox("pdffile", "", new { type = "file", accept = "application/pdf" })
</div>
<br />
<br />
<div class="editor-field">
<input type="button" id="btnfileUpload" 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="@file.filepath">View Pdf</a></td>
</tr>
}
}
</table>
</div>
</fieldset>
<script>
$(document).ready(function(){
$('#btnfileUpload').click(function () {
if (window.FormData !== undefined) {
var fileUpload = $("#pdffile").get(0);
var files = fileUpload.files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
$.ajax({
url: '/FileUpload/UploadPdfFiles',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
alert(result);
window.location.reload();
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("Your browser doesn support FormData");
}
});
});
</script>
}
Uploading Multiple pdf files in Asp .net Mvc
if you wan to upload multiple pdf file then you can use the below code.
you only need to change action controller code with below one,
//For Uploading Multiple files at once
[HttpPost]
public ActionResult UploadMultiplePdfFiles()
{
// Checking if Request object has file
if (Request.Files.Count > 0)
{
try
{
HttpFileCollectionBase files = Request.Files;
//in case if you want upload the multiple pdf files
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
string fname = file.FileName;
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/PdfFiles/"), fname);
file.SaveAs(fname);
}
return Json("Pdf Uplaoded Successfully!");
}
catch (Exception ex)
{
return Json(ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
Result
The post [Solved]-How to Upload pdf file using jquery MVC? appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- Simple Way Find and replace text in Word document using C#
- Implementing “Remember Me” Feature in ASP.NET MVC
- [Solved]-Cookie loses value when page is changed in MVC
- How to post File Upload and other form fields to one action Asp .Net MVC C#
- How To Post File and Data to API using HttpClient C#
- Create ASP.NET Core Web API Without Entity Framework
- .NET Core Web API Using Code First Entity Framework Approach
- Create Asp.Net Core Web Api Using Entity Framework Database First
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- CRUD operation using partial view in MVC with modal popup
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- Crud Operations in MVC Without Entity Framework
- Create Login,Signout and Registration in Asp .Net Mvc Using Entity
- Export Gridview to Excel and Csv in Asp .Net With Formatting Using c#
- How to Display Binary Image in Gridview from Database in Asp .Net c#
- [Solved]-How to Upload pdf file using jquery MVC?
- [Solved]-Uploading both data and files in FormData using Ajax MVC
- C# -Saving a base64 string as an image into a folder on server in Web Api
- [Solved]-Download pdf file from link and save in local file folder in Asp .Net
- [Solved]-Delete Files older than X Months,Days,Minute in a Directory- C# .NET
- [Solved]-LEFT OUTER JOIN in LINQ With Where clause in C#
- INNER JOIN,RIGHT JOIN,LEFT JOIN USING LINQ IN Multiple Table C#
- [Solved]-Convert Base64 To Image And Save in folder and Display it- C#
- [Solved]-How to Overlay Two Images in .NET-C#
- How to Create Multilingual Website in Asp .Net
- C# – How to add double quotes to a string that is inside a variable
- Update an Image with Upload Button For Each Row in Gridview-Asp .Net
- How to Bind Data in DataList Control in Asp.Net – C#
- Upload and Display an Image in Gridview From Image Path in Database -C#