How to show multiple images selected "input file"?

1

Here is an example: link

When you select 4 different images, the 4 images are the same as the on-screen display.

HTML:

<form id="form1" runat="server">
    <input type='file' id="imgInp" multiple />
    <img id="blah" src="#" width="100" />

    <img id="blah1" src="#" width="100" />

    <img id="blah2" src="#" width="100" />

    <img id="blah3" src="#" width="100" />
</form>

JS:

 function readURL(input) {        

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

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
                $('#blah1').attr('src', e.target.result);
                $('#blah2').attr('src', e.target.result);
                $('#blah3').attr('src', e.target.result);
            }

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

    $("#imgInp").change(function(){
        readURL(this);
    });
    
asked by anonymous 23.11.2016 / 20:51

1 answer

1

There are some flaws in your code; in my view, the correct thing would be for you to learn how it works and redo. Follow this explanatory code.

The first logic of all is to set up the html. The first defect found in your code is <input type='file' id="imgInp" multiple /> where you would like to have set the name property to receive the keys.

Correcting this part, you should do something like this

<input type="file" id="file" name="files[]" multiple />
<div class="resultados"></div>

Another problem in your code is that you are creating 4 divs, each to receive a different image, another defect, since you can only create a div to receive the values; works the same, works and is better.

To solve this, in the code above I put only a div called resultados that will receive all the images.

Now your Javascript is where the biggest flaw is. You are always playing the first key for both divs.

The correct thing is for you to do it this way

  function readURL(evt) {
    var files = evt.target.files;

    for (var i = 0, f; f = files[i]; i++) {

      if (!f.type.match('image.*')) {
        continue;
      } //verifica se os arquivos são imagens

      var reader = new FileReader();

      reader.onload = (function(filei) {
        return function(e) {

          var tag = document.createElement('span');
          tag.innerHTML = ['<img src="', e.target.result,
                            '" title="', escape(filei.name), '"/>'].join('');
          document.getElementById('resultados').insertBefore(tag, null);
        };
      })(f);
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('file').addEventListener('change', readURL, false);

You can view this code in action at JsFiddle .

    
23.11.2016 / 21:59