简体   繁体   English

FileUpload复制文件

[英]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 我正在做一个简单的测试,只是尝试上传一个文件,将其转换为未签名的8数组,然后将其记录在控制台上

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 第一次单击时,控制台显示1个输出

on the second click the console shows 2 outputs repeated 在第二次单击上,控制台显示重复的2个输出

on the third click the console shows 3 outputs repeated 在第三次单击控制台上,重复显示3个输出

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. 每次您单击按钮时,都将附加一个新的.change事件。 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 : 只要将.change外部事件.click类似事件这样小提琴

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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