Preview image with JS

2

I'm trying to do an image preview when the user selects the file with <input type="file" /> but I'm having a lot of difficulty, I've looked in several places and since I do not handle a lot of Front it's even harder for me!

I tried to like this post I did not succeed. Does anyone have another method?

    
asked by anonymous 11.09.2015 / 22:35

2 answers

1

Follow 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"/>

Response link in SOen: link

    
11.09.2015 / 23:14
1

To accomplish this task I advise you to use some APIs like fileinput , as mentioned in the link you has gone above, since it already has CSS implemented and is already very stable. But even so it follows a solution using jQuery, if you want only with pure JavaScript, please tell us 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 it working here :)

And if you want to risk something different, here's the FileReader documentation :)

    
11.09.2015 / 23:38