Pdf preload with Javascriipt or Jquery

Asked

Viewed 152 times

3

I have an input file type and I need to generate a Preload partially showing the content of the pdf. I have the following code

 <label for="">Selecione o arquivo de orçamento</label>
    <input type="file" name="files[]" class="form-control form-control-sm" onchange="verifyMimes(this)" required>
     <img id ="Tela" Name ="Tela"/>

Follows the script

  function verifyMimes($input) {
        let allowed = ['jpg', 'png', 'jpeg', 'pdf', 'PDF'];
        let fileExtension = $input.value.split('.').pop();
        if (typeof allowed.find(function (ext) { return fileExtension == ext; }) == 'undefined') {
            $('#alert-pdf').text('O arquivo de diagnóstico deve possuir o formato jpg, png, jpeg ou pdf')
            $('#pdf-send').prop('disabled', true);
        } else {

            $('#pdf-send').prop('disabled', false);
            $('#alert-pdf').text('')

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

                reader.onload = function (e) {
                    $('#Tela').attr('src', e.target.result);
                }
                console.log($input.files[0])
                reader.readAsDataURL($input.files[0]);
            }
        }
    }

It displays if the file is a jpg, png or jpeg, but wanted to perform the Preload of a pdf. Anyone knows how it would be possible to perform this procedure?

1 answer

4


You need to create a condition for when it is a PDF file, it use the tag iframe, follow the method as I would:

function preloadFile($input) {

        const screen = $('#preLoad');
        if ($input.files.length <= 0)
            return;

        const { type } = $input.files[0];
        const reader = new FileReader();

        reader.onload = function (e) {
            if (type != 'application/pdf')
                screen.html(`<img src="${e.target.result}"/>`)
            else
                screen.html(`<iframe src="${e.target.result}"/>`)
        }
        reader.readAsDataURL($input.files[0]);
    }

HTML would look like this:

<label for="">Selecione o arquivo de orçamento</label>
<input type="file" name="files" class="form-control form-control-sm" 
onchange="preloadFile(this)" required>
<div id="preLoad"></div>

I advise to create the mimes check in another method and call it in the method preloadFiles

  • It worked perfectly without any error. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.