Multiple Image Preview using jQuery PHP |
This tutorial will teach you how to preview multiple images before uploading using jQuery.
Note: jQuery used in this tutorial is hosted, so, you might need internet connection for it to work.
index.html
This contains our input file that we have customize and our preview area.
<!DOCTYPE html> <html> <head> <script src="<a href="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <style> body{ font-family: 'Open Sans', sans-serif; } .button { background-color: #4CAF50; border: none; color: white; padding: 16px 32px; text-align: center; text-decoration: none; font-size: 16px; margin: 4px 2px; cursor:pointer; font-family: 'Open Sans', sans-serif; } .main{ margin-top:50px; } .hidden{ display:none; } .h10{ height:10px; } #filetext{ margin-left:10px; } .title{ font-size:25px; } .container { margin : 50px auto 0 auto; width:50%; } #filebutton{ margin : 50px auto 0 auto; } #preview{ margin-top:50px; } </style> </head> <body> <div id="container"> <div class="main"> <input type="file" name="file" id="file" class="hidden" multiple> </div> </div> </body> </html>
custom.js
This contains our jQuery for the input file custom and image preview.
$(document).ready(function(){ $('#filebutton').click(function(){ $('#file').click(); }); $('#file').change(function(){ var name = $(this).val().split('\\').pop(); var file = $(this)[0].files; if(name != ''){ if(file.length >=2){ $('#filetext').html(file.length + ' files ready to upload'); } else{ $('#filetext').html(name); } } }); $('#file').on("change", previewImages); }); function previewImages() { var $preview = $('#preview').empty(); if (this.files) $.each(this.files, readAndPreview); function readAndPreview(i, file) { if (!/\.(jpe?g|png|gif)$/i.test(file.name)){ return alert(file.name +" is not an image"); } // else... var reader = new FileReader(); $(reader).on("load", function() { $preview.append($("<img>", {src:this.result, height:200})); }); reader.readAsDataURL(file); } }