Image Preview with JS

Asked

Viewed 1,224 times

2

I am trying to make an image preview when the user selects the file with the <input type="file" /> but I’m having a lot of trouble, I’ve looked in several places and as I don’t know much about Front it’s even more difficult for me!

I tried to make same as this post but I was unsuccessful. Someone has another method?

2 answers

3


Follows the code:

  var loadFile = function(event) {
    var output = document.getElementById('output');
    output.src = URL.createObjectURL(event.target.files[0]);
  };
<input type="file" accept="image/*" onchange="loadFile(event)"/>
<img id="output"/>

Reply link on Soen: link

1

To accomplish this task I advise you to use some API like fileinput, as it was mentioned in the link you passed above, as it already has CSS implemented and is already very stable. But even so follows a solution with use of jQuery, if you want only with pure Javascript let us know in the comments:

HTML:

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>

Javascript:

function leUrl(input) {
    if (input.files && input.files[0]) { //verifica se o arquivo não está nulo
        var reader = new FileReader(); //instancia um objeto FileReader que permite aplicações web ler o conteúdo dos arquivos (ou buffers de dados puros)

        reader.onload = function (e) { //Este evento é chamado cada vez que a operação de leitura é completada com sucesso.
            $('#blah').attr('src', e.target.result); //aqui seto a imagem no src da div a cima
        }

        reader.readAsDataURL(input.files[0]); //Inicia a leitura do conteúdo que caira após o peração completar na função a cima
    }
}

$("#imgInp").change(function () { //aqui seto a função no evento de change do campo
    leUrl(this);
});

See working here :)

And if you want to risk something different, here’s the documentation from Filereader :)

Browser other questions tagged

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