Sometimes, in a project, we require a reporting module where users or admins can upload and download specific types of files with limitations.

Recently, I had the opportunity to work on such modules, specifically focusing on the admin module. Here, the goal is to allow users to upload and download PDF files.

In this article, I aim to guide beginners and those who need to upload and download PDF files in a tabular view using MVC Ajax calls. Additionally, we will discuss how to upload multiple PDF files using Ajax in MVC.

Let's begin by creating an MVC application to upload and download PDF files step-by-step. Start by creating an empty MVC Project in Visual Studio.

I have also created a folder to store uploaded PDF files on the server.

Uploading both data and files in one form using Ajax MVC
Now let’s add controller in our project for uplaoding files

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.");
            }
        }
    }
}

1. The `Index` action method is responsible for displaying the list of uploaded files. It retrieves the list of files from the specified directory (`PdfFiles`) and constructs a list of `FilesInformation` objects, which is then passed to the view for rendering.
2. The `UploadPdfFiles` action method handles the HTTP POST request for uploading PDF files. It checks if any files are uploaded and, if so, saves the first file to the specified directory (`PdfFiles`). It returns a JSON response indicating success or failure.
3. If files are uploaded successfully, it returns a JSON response indicating that the PDF file was uploaded successfully. If there's an exception during the file upload process, it returns a JSON response with the error message.
4. If no files are uploaded, it returns a JSON response indicating that no files were selected.
This controller provides functionality for displaying the list of uploaded files and handling the upload of PDF files. It ensures proper handling of file uploads and exceptions while returning appropriate JSON responses.
View Html Code
The process of uploading a PDF file in an ASP.NET MVC application is simple and quick. We can achieve this task easily. The posted PDF file is automatically available as a `HttpPostedFileBase` parameter in the action method of the controller.
To upload a PDF file on the server, you need to have a file input control within an HTML form with the 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 want to upload multiple PDF files, you can use the following code. You only need to replace the action controller code with the code below.

  • This action method, UploadMultiplePdfFiles, is responsible for handling the HTTP POST request for uploading multiple PDF files at once.
  • It first checks if the request object contains any files by checking the Request.Files.Count.
  • If files are found, it iterates through each file in the Request.Files collection using a for loop.
  • Inside the loop, it retrieves each file using HttpPostedFileBase file = files[i], then gets the filename and constructs the complete file path where the file will be stored on the server.
  • After constructing the file path, it saves the file using file.SaveAs(fname).If all files are successfully uploaded, it returns a JSON response indicating that the PDF files were uploaded successfully.
  • If any exception occurs during the file upload process, it returns a JSON response containing the error message.
  • If no files are selected, it returns a JSON response indicating that no files were selected for upload.

//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.");
            }
        }

Download Source Code 

Result