Display multiple input images with Jquery

0

I'd like to know how I can display the images that were selected in my input multiple. I already tried to find something of the type but only found how to get the name, size, type. Ob

    
asked by anonymous 08.03.2017 / 14:17

2 answers

2

Based on Mathias answer, I've made an example that fits your question better because you have a multiple input, not just one file at a time, as in the answer. Just add a loop that goes through all the selected files and images via Append on the form: link

Html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="form1" runat="server">
  <input type='file' id="inputImg" multiple/><br>

</form>

JS:

    $("#inputImg").change(function() {
      readURL(this);
    });

    function readURL(input) {
      if (input.files && input.files[0]) {
         for(x in input.files){
        var reader = new FileReader();
                reader.readAsDataURL(input.files[x]);
        reader.onload = function(e) {
          $('<img style="max-width:50px">').appendTo("form").attr('src',        e.target.result);
        }

      }
   }
}
    
09.03.2017 / 14:41
2

I believe that the code below is what you are looking for, whenever there is any change in the input a function is called that reads and displays the stored file if possible.

$("#inputImg").change(function() {
  readURL(this);
});

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('#img').attr('src', e.target.result);
    }
    reader.readAsDataURL(input.files[0]);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="form1" runat="server">
  <input type='file' id="inputImg" /><br>
  <img id="img" style="border:1px solid grey;" />
</form>
    
08.03.2017 / 18:11