Shubham Jha Shubham Jha - 29 days ago 15
HTML Question

Display multiple images in preview

I have this form where I can select multiple images and preview the selected images before submitting the form. But only 1 image is being displayed. I want to display all the selected images. Please help.

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server">
<div style="display: inline-flex">
<div style="width: 160px">
<input type="file" name="file-5[]" id="file-5" class="inputfile inputfile-4" data-multiple-caption="{count} files selected" multiple />
<label for="file-5">
<span style="display: none;">Choose a file&hellip;</span></label>
<img id="status-img" src="#" alt="" width="150" height="150" /><br />
<input type="submit" name="post" value="Post" class="post-btn" id="submit" />
</div>
</form>


Javascript:

<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#status-img').attr('src', e.target.result);
$('.removeimg').fadeIn();
}
reader.readAsDataURL(input.files[0]);
}
}

$("#file-5").change(function(){
readURL(this);
});
</script>

Answer

You have to loop the number of selected images and play with the data.

HTML CODE: Add preview div.

<div id="imgs"></div>

JS Code :

 $("#file-5").on('change',function() {
 var fileList = this.files; 
 for(var i = 0; i < fileList.length; i++)
 {
      //get a blob 
      var t = window.URL || window.webkitURL;
      var objectUrl = t.createObjectURL(fileList[i]);
      $('#imgs').append('<img src="' + objectUrl + '" />');

      j = i+1;
      if(j % 3 == 0)
      {
        $('#imgs').append('<br>');
      }

 }
});
Comments