[Solved]-How to Upload pdf file using jquery mvc 4

[Solved]-How to Upload pdf file using jquery mvc 4

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.

Now Let’s add a controller and View to our Project

View Html Code

@model  IEnumerable<WebAppMvc.Controllers.FilesInoformation>

@{
    ViewBag.Title = "";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
@using (Html.BeginForm("UploadPdf", "Home", 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: '/Home/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>
}

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 string filepath { 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, filepath = "/PdfFiles/" + file.Name });
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult UploadPdfFiles()
        {
            // 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

Ashok Patel

I'm an electronic engineer working in a multinational company,having good experience on Electronics and electrical engineers design and oversee production of electronic equipment such as radios, televisions, computers, washing machines and telecommunication systems.I like to do RND and Research.I also have hands on experience graphic design software and in web designing having great command on ASP.NET, HTML5, JavaScript, T-SQL, JQuery.

Add comment

Donate for Corona Victim

Corona Virus Relief Fund

Your Header Sidebar area is currently empty. Hurry up and add some widgets.