Preview and download PDF from byte array using jQuery Ajax in ASP.Net Core MVC

AbdulHaque
 
on Oct 14, 2021 06:36 AM
Sample_210417.zip
979 Views

Hello @everyone

I have asp.net core mvc application in which using jQuery ajax

I am allowing user to view and download pdf files generated from byte array.

My code works perfectly fine in Chrome and FF but when in Internet explorer both download and preview is not working.

Please help me out below is my code any suggestions will be appritiated.

// For preview JS
function GetDocPreview(fileLeafRef, ID, SitePath, FileUrl) {
    var urlPrv = $('#urlPrv').data('request-url');
    $.ajax({
        type: "POST",
        url: urlPrv, // do not hard code your url's
        data: {
            'fileLeafRef': fileLeafRef, 'ID': ID, 'SitePath': SitePath, 'FileUrl': FileUrl, 'DeptSiteColID': $("#DeptSiteColID").val(), 'staffID': $("#hdnStaffID").val()
        },
 
        success: function (data, jqXHR, response) {
            if (data.success) {
                var bytes = _base64ToArrayBuffer(data.message);
                // saveByteArray("Sample Report", bytes);
                var getFile = new Blob([bytes], { type: data.type });
                var fileURL = URL.createObjectURL(getFile);
                $("#embedPreview").attr('src', fileURL);
 
            }
        }
    });
}

 

//For download files 
$(document).on('click', '#download', function () {
    var ID = $(this).attr('file-id');
    var filename = this.innerHTML;
    var urlPath = this.attributes[2].nodeValue;
    if (urlPath == '#') {
        urlPath = this.attributes[3].nodeValue;
    }
    var urlPrv = $('#urldownload').data('request-url');
    $.ajax({
        type: "POST",
        url: urlPrv, // do not hard code your url's
        data: { 'fileLeafRef': filename, 'ID': ID, 'SitePath': urlPath, 'FileUrl': urlPath, 'DeptSiteColID': $("#DeptSiteColID").val(), 'staffID': $("#hdnStaffID").val() },
        success: function (data, jqXHR, response) {
            if (jqXHR == "success") {
                var bytes = _base64ToArrayBuffer(data.message);
                saveByteArray(filename, bytes);
                var blob = new Blob([bytes], { type: data.type });
                var fileURL = URL.createObjectURL(blob);
 
 
            }
        }
    });
});
 
function saveByteArray(reportName, byte) {
    var blob = new Blob([byte], { type: "application/pdf" });
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    var fileName = reportName;
    link.download = fileName;
    link.click();
};

//Base64 conversion
function _base64ToArrayBuffer(base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Oct 16, 2021 04:49 AM
on Oct 19, 2021 07:48 AM

Hi AbdulHaque,

Refer below code.

For more details on download file using jQuery ajax refer below article.

Download File as BLOB using AJAX and jQuery

Controller

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult AjaxMethod()
    {
        byte[] bytes;
        string fileName, contentType;
        string constr = @"Server=.;DataBase=DBFiles;UID=sa;PWD=pass@123";
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select Name, Data, ContentType from tblFiles where Id=1002";
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    sdr.Read();
                    bytes = (byte[])sdr["Data"];
                    contentType = sdr["ContentType"].ToString();
                    fileName = sdr["Name"].ToString();
                }
                con.Close();
            }
        }

        return Json(new { filename = fileName, message = Convert.ToBase64String(bytes) });
    }
}

View

@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <input id="preview" type="button" value="Preview" />
    <input id="download" type="button" value="Download" />
    <hr />
    <iframe id="embedPreview"></iframe>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).on('click', '#preview', function () {
            $.ajax({
                type: "POST",
                url: "Home/AjaxMethod",
                data: {},
                success: function (data, jqXHR, response) {
                    if (jqXHR == "success") {
                        var isIE = false || !!document.documentMode;
                        if (isIE) {
                            var bytes = _base64ToArrayBuffer(data.message);
                            saveByteArray(data.filename, bytes);
                        } else {
                            $("#embedPreview").attr('src', 'data:application/pdf;base64,' + data.message);
                        }
                    }
                }
            });
        });

        $(document).on('click', '#download', function () {
            $.ajax({
                type: "POST",
                url: "Home/AjaxMethod",
                data: {},
                success: function (data, jqXHR, response) {
                    if (jqXHR == "success") {
                        var bytes = _base64ToArrayBuffer(data.message);
                        saveByteArray(data.filename, bytes);
                    }
                }
            });
        });

        function _base64ToArrayBuffer(base64) {
            var binary_string = window.atob(base64);
            var len = binary_string.length;
            var bytes = new Uint8Array(len);
            for (var i = 0; i < len; i++) {
                bytes[i] = binary_string.charCodeAt(i);
            }
            return bytes.buffer;
        }

        function saveByteArray(reportName, byte) {
            var blob = new Blob([byte], { type: "application/octetstream" });
            var isIE = false || !!document.documentMode;
            if (isIE) {
                window.navigator.msSaveBlob(blob, reportName);
            } else {
                var url = window.URL || window.webkitURL;
                link = url.createObjectURL(blob);
                var a = $("<a />");
                a.attr("download", reportName);
                a.attr("href", link);
                $("body").append(a);
                a[0].click();
                $("body").remove(a);
            }
        };
    </script>
</body>
</html>
dharmendr
 
on Oct 19, 2021 07:49 AM

Modern browsers like chrome, firefox, edge and other comes with a PDF viewer.

But IE doesn't have. So if user uses IE let them download the file and view in installed application.