Reputation: 1963
Im making a simple test, just trying to upload a file, convert it to unsigned 8 array then log it on the console
My code works perfectly but every time i push the button to upload a file, the console incrementally repeats the output, let me explain:
on the first click the console shows 1 output
on the second click the console shows 2 outputs repeated
on the third click the console shows 3 outputs repeated
and so on...
Can you help me to spot the error? My code is:
<button type="button" class="btn btn-primary" id="bid_uploadPicture">Subir Imagen</button>
<input type="file" id="file" style="display:none;" />
jQuery(function ($) {
$("#bid_uploadPicture").click(function () {
event.preventDefault();
document.getElementById("file").click();
var fr = new FileReader();
$("#file").change(function () {
fr.onload = imageIsLoaded;
fr.readAsArrayBuffer(this.files[0]);
});
});
});
function imageIsLoaded(e) {
data = new Uint8Array(e.target.result)
console.log(e.target.result);
}
Upvotes: 1
Views: 180
Reputation: 7593
Every time you click on the button, you're attaching a new .change
event. This means they add up; two clicks = two listeners waiting for a file change.
Just move the .change
event outside the .click
event like this fiddle:
jQuery(function($) {
$("#bid_uploadPicture").click(function() {
event.preventDefault();
document.getElementById("file").click();
});
var fr = new FileReader();
$("#file").change(function() {
fr.onload = imageIsLoaded;
fr.readAsArrayBuffer(this.files[0]);
});
});
function imageIsLoaded(e) {
data = new Uint8Array(e.target.result)
console.log(e.target.result);
}
Upvotes: 2