Javascript Ajax jQuery Html PHP Example Quiz New MORE

Image File preview before upload using jQuery with demo


In this example if we upload a image file it previews the image before uploading(For single image file).

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<input type="file" accept="image/*" onchange="showMyImage(this)" />
<br/>
<img id="thumbnil" style="width:20%; margin-top:10px;" src="" alt="image"/>
<script>
function showMyImage(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img=document.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
}
</script>

In this example if we upload multiple image file it previews the image before uploading(For Multiple image file).

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
</script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery">

Run it yourself

Demo


image