Change src attribute of an image when uploading via file type input

2

Hey guys, blz?

I need a code that when uploading an image via input file type it is displayed in a preview type.

What I have so far is this:

HTML:

<div class="card">
    <img class="card-img-top" src="<?=$foto?>" id="fotopreview">
        <div class="card-body">

            <h4 class="card-title">Alterar foto do aluno</h4>

            <p class="card-text">Selecione uma imagem no botão abaixo</p>

            <input type="file" class="form-control-file" name="foto" id="uploadfoto">

        </div>
</div>

JS:

    uploadfoto = document.getElementById('uploadfoto');
    fotopreview = document.getElementById('fotopreview');

    uploadfoto.addEventListener('change', function(e) {
        showThumbnail(this.files);
    });

    function showThumbnail(files) {
        if (files && files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#fotopreview').attr('src', e.target.result);
        }

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

This code does not even change the src attribute of the "photopreview" element.

Can someone give you a hand?

Vlw!

    
asked by anonymous 03.11.2017 / 20:21

1 answer

2

It seems to me that in your case the error may be happening due to lack of JQuery, follows the pure javascript excerpt (jquery was only being used on a single line)

var uploadfoto = document.getElementById('uploadfoto');
var fotopreview = document.getElementById('fotopreview');

uploadfoto.addEventListener('change', function(e) {
    showThumbnail(this.files);
});

function showThumbnail(files) {
    if (files && files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
       fotopreview.src = e.target.result;
    }

        reader.readAsDataURL(files[0]);
    }
}
<div class="card">
    <img class="card-img-top" src="<?=$foto?>" id="fotopreview">
        <div class="card-body">

            <h4 class="card-title">Alterar foto do aluno</h4>

            <p class="card-text">Selecione uma imagem no botão abaixo</p>

            <input type="file" class="form-control-file" name="foto" id="uploadfoto">

        </div>
</div>
    
03.11.2017 / 20:57