How to load and view a local image

3

How can I show an image in img by selecting the file with input type file ?

<img id="img1" src="" height="100px" width="100px" border="solid 1px">
    <input id="inputFile1" type="file">

    <script>
        window.addEventListener('load', init, false);

        function init() {
            var inputFile = document.querySelector('#inputFile1');
            inputFile.addEventListener('change', mostrarImagen, false);
        }

        function mostrarImagen(e) {
            var img = document.querySelector('#img1');
            var inputFile = document.querySelector('#inputFile1');
            img.src = inputFile.value;
        }
    </script>
    
asked by Neyer 03.01.2017 в 19:41
source

1 answer

5

Using the API FileReader ( IE10+ ) of HTML5

function init() {
  var inputFile = document.getElementById('inputFile1');
  inputFile.addEventListener('change', mostrarImagen, false);
}

function mostrarImagen(event) {
  var file = event.target.files[0];
  var reader = new FileReader();
  reader.onload = function(event) {
    var img = document.getElementById('img1');
    img.src= event.target.result;
  }
  reader.readAsDataURL(file);
}

window.addEventListener('load', init, false);
<img id="img1"><br/>
<input id="inputFile1" type="file">
    
answered by 03.01.2017 / 19:59
source