FileReader中的Javascript变量未持久化
我正在构建一个web应用程序,在上传到服务器之前需要进行一些文件验证和编码检查。因此,FileReader在这方面很好,但变量中的值不会持久化,即使变量在每个函数之外声明:我有以下代码,works unitl testDesc函数:FileReader中的Javascript变量未持久化,javascript,html,Javascript,Html,我正在构建一个web应用程序,在上传到服务器之前需要进行一些文件验证和编码检查。因此,FileReader在这方面很好,但变量中的值不会持久化,即使变量在每个函数之外声明:我有以下代码,works unitl testDesc函数: var fileDesc1; var fileDesc2; window.onload = function () { checkFile(); testDesc(); }//window onload function checkFile()
var fileDesc1;
var fileDesc2;
window.onload = function () {
checkFile();
testDesc();
}//window onload
function checkFile() {
//input type=file
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload= function (e) {
var contents = reader.result;
fileDesc1 = arrayToString(contents);
fileDesc2 = discoverType2File(fileDesc1);
...
}
reader.readAsArrayBuffer(file);
}
在我获得文件描述后,我需要它们在JS代码中的任何地方都可用,但事实并非如此:
function testDesc(){
//fileDesc1 is empty
encode(fileDesc1);
...
return validatyCheck
}
所有函数都在同一个文件中,但变量为空。为什么会这样?我以为我知道JS,但我猜不知道。顺便说一句,所有js文件都加载在html主体标记的末尾。可能重复的
testDesc
在reader之前执行。onload
@Xufox您的意思是调用是异步的吗?刚刚发现FileReader是异步的testDesc
可能重复的在reader.onload
@Xufox之前执行你是说调用是异步的?刚刚发现FileReader是异步的