FileUpload复制文件 [英] FileUpload duplicating files
问题描述
我正在做一个简单的测试,只是尝试上传一个文件,将其转换为未签名的8数组,然后将其记录在控制台上
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:
在第一次单击时控制台显示1个输出
on the first click the console shows 1 output
第二次单击控制台,重复显示2条输出
on the second click the console shows 2 outputs repeated
第三次单击控制台,重复显示3个输出
on the third click the console shows 3 outputs repeated
以此类推...
您能帮我发现错误吗?我的代码是:
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);
}
推荐答案
每次单击按钮时,都会附加一个新的.change
事件.这意味着他们加起来;两次单击=两个侦听器正在等待文件更改.
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.
只需将.change
事件移到.click
事件之外,例如此小提琴:
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);
}
这篇关于FileUpload复制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!