article

Tuesday, July 21, 2015

Image Preview Thumbnails before upload using jQuery & PHP

Image Preview Thumbnails before upload using jQuery & PHP
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script>
$(document).ready(function(){
    $('#file-input').on('change', function(){ //on file input change
        if (window.File && window.FileReader && window.FileList && window.Blob) //check File API supported browser
        {
            $('#thumb-output').html(''); //clear html of output element
            var data = $(this)[0].files; //this file data
            
            $.each(data, function(index, file){ //loop though each file
                if(/(\.|\/)(gif|jpe?g|png)$/i.test(file.type)){ //check supported file type
                    var fRead = new FileReader(); //new filereader
                    fRead.onload = (function(file){ //trigger function on successful read
                    return function(e) {
                        var img = $('<img/>').addClass('thumb').attr('src', e.target.result); //create image element 
                        $('#thumb-output').append(img); //append image to output element
                    };
                    })(file);
                    fRead.readAsDataURL(file); //URL representing the file's data.
                }
            });
            
        }else{
            alert("Your browser doesn't support File API!"); //if File API is absent
        }
    });
});
</script>
<style>
.thumb{
    margin: 10px 5px 0 0;
    width: 100px;
}
.alert-info {
  background-color: #d9edf7;
  border-color: #bce8f1;
  color: #31708f;
}
.alert {
  padding: 5px 10px;
  margin-bottom: 10px;
  border: 1px solid transparent;
  border-radius: 4px;
}
</style>
<div class="alert alert-info">
<input type="file" id="file-input" multiple=""><p></p>
<div id="thumb-output"></div>
</div>

Related Post