简体   繁体   中英

FileUpload duplicating files

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);
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM