Display Image and PDF file preview in Bootstrap modal popup using jQuery in ASP.Net MVC

Dorababu
 
on Nov 07, 2021 07:04 PM
745 Views

I have a table where I am storing the file to NVARCHAR(MAX).

I would like to create a partial view which will open as a modal and display the required content from database and show the content. The popup will also have download button so that when user click it should download the respective file

I am trying with both approaches I am able to display images I would like to show the pdf

context.EnvironmentAttachments.Where(x => x.EnvironmentAttachmentId == attachmentId).FirstOrDefault();
attachment.AttachmentName = env.AttachmentName;
attachment.AttachmentType = env.AttachmentType;
attachment.AttachmentData1 = env.AttachmentData;
attachment.AttachmentData = Convert.FromBase64String(env.AttachmentData);

 

public class Attachment
{
    public int AttachmentId { get; set; }
    public string AttachmentName { get; set; }
    public string AttachmentType { get; set; }
    public byte[] AttachmentData { get; set; }
    public string AttachmentData1 { get; set; }
}

My Jquery code

function ShowDoc(tableName, Id) {
    var data = JSON.stringify({
        'tableName': tableName,
        'attachmentId': Id
    });
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        contentType: 'application/json',
        dataType: "json",
        success: function (data) {
            $("#attachmentId").val(data.split(";")[4]);
            $("#tableName").val(data.split(";")[3]);
            $("#fileData").html();
            if (data.split(";")[2] === "image/jpeg") {
                $("#exampleModal").modal("show");
                $("#exampleModalLabel").text(data.split(";")[0]);
                var img = document.createElement("img");
                img.src = "data:image/jpeg;base64," + data.split(";")[1];
                $("#fileData").html(img);
            }
            else {
                if (data.split(";")[2] === "application/pdf") {
                    $("#exampleModal").modal("show");
                    $("#exampleModalLabel").text(data.split(";")[0]);
                    var makeIframe = document.createElement("embed");
                    makeIframe.setAttribute("src", "data:application/pdf;base64," + data.split(";")[1]);
                    $("#fileData").html(makeIframe);
                }
            }
        }
    });
}

Working for images but not pdf

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 10, 2021 09:00 PM
Dorababu says:
$("#fileData").html(makeIframe);

You need to append the iframe to the control instead of html.

$("#fileData").append(makeIframe);

Or use below.

$("#fileData").append('<iframe src="data:application/pdf;base64,"' + data.split(";")[1] + '></iframe>');