1

I would like to display a preview of a pdf before upload. It works on firefox but not on chrome. If I try with an image, it works on both.

Here my code:

<input required="required" accept="image/*, application/pdf" class="uploadjs" data-id="3" type="file">

<div class="preview">
  <img id="preview-3" alt="">
  <embed id="preview-3_1" type="application/pdf">
</div>


function readURL(input, id) 
{
    var mime= input.files[0].type;

    if (input.files && input.files[0]) 
    {
        var reader = new FileReader();

        reader.onload = function (e) 
        {
            if(mime.split("/")[0]=="image")
            {
                $('#preview-'+id+'_1').attr('src', '');
                $('#preview-'+id).attr('src', e.target.result);

            }
            else
            {
                $('#preview-'+id).attr('src', '');
                $('#preview-'+id+'_1').attr('src', e.target.result);
            }
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$(function()
{
    $(".uploadjs").change(function()
    {
        var id = $(this).data('id')
        readURL(this, id);
    });
})

And a jsfiddle: https://jsfiddle.net/g9ttqxyj/2/

I have tried multiple ideas like: embed, iframe and object but none works on chrome.

MisterDebug
  • 915
  • 9
  • 15

1 Answers1

1

For anyone stumbling upon this: Encapsulate your embed tag with an object tag. The data attribute of the object tag has to link to the .pdf. Change html to:

<object type="application/pdf" data ="#" id="pdfViewer">
    <embed id="preview-3_1" type="application/pdf">
</object>

Add this to your jquery:

$('#pdfViewer').attr('data',  e.target.result);

https://stackoverflow.com/a/23681394

WBuyt
  • 11
  • 2
  • This almost worked for me. Slight change if you're using Vue or other frameworks, bind data e.g. `:data="myPDFData"` and set `myPDFData=URL.createObjectURL(event.target.files[0])` where `event.target.files[0]` is from an `` tag – Soubriquet Mar 12 '22 at 01:02