Display Multiple input images with Jquery

Asked

Viewed 549 times

0

I would like to know how to present the images that were selected in my Multiple input. I’ve tried to find something of the kind but only found how to get the name, size, type. Ob

2 answers

2

I believe the code below is what you are looking for, whenever there is any change in the input is called a function 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>
<form id="form1" runat="server">
  <input type='file' id="inputImg" /><br>
  <img id="img" style="border:1px solid grey;" />
</form>

2


Based on a friend’s response Mathias, I made an example that fits your question better because you have a Multiple input and not just one file at a time as in the answer. Just add a loop that goes through all the selected files and the images through Append in the form: https://jsfiddle.net/y5j694vz/

Html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="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);
        }

      }
   }
}

Browser other questions tagged

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