I am creating a file uploader where a user selects the pics one by one using a file input and its added to a tray(preview) using the HTML file reader API.
My problem is when the first picture is selected its added to the tray once correctly when the second photo is selected is added twice when the third is selected its added thrice. This implies n previews for the nth photo. I don't know what am doing wrong please help.
//Event handler for image upload button click
$('body').on('click', '#add-default-pic', function (event) {
event.preventDefault();
$('#default-pic-chooser').trigger('click');
//Wait for #photo file input to change
$('#default-pic-chooser').on('change', function () {
if ($('#default-pic-chooser').val() !== '') {
//Do checks to see if photo is valid
if (isImage($('#default-pic-chooser').val())) {
} else {
$('.info').html('Sorry your picture format is not supported');
$('#infoModal').modal();
return;
}
}
if (typeof (FileReader) != 'undefined') {
reader = new FileReader();
//Run this function when file is ready
reader.onload = function (e) {
img = e.target.result;
$('.default-pics-area').append('<img src="' + img + '" style="padding:0px; width:auto; height:auto; max-width:100%; max-height:150px;"/>');
// alert("whats on:"+img);
if ($('#default-pic-chooser').val() !== '') {
var route = base + '/pics/default/upload';
var photo = document.getElementById('default-pic-chooser').files[0]; //grapping photo file
// uploadPhoto(route,photo);
upload(route, photo, 'photo');
}
};
//Trigger the onload function
reader.readAsDataURL($(this) [0].files[0]);
} else {
alert('OOPS! you wont be able to preview your image because your browser does not support this feature...');
}
});
});
Remove $('#default-pic-chooser').on('change'....)
out of the body's click handler.
Because everytime you click #add-default-pic
,you add a new change
handler function to the #default-pic-chooser
.So,when you trigger click
,it will trigger the functions one by one.