Javascript 图像上传测量的闭包问题
为了在上传时检查上传的img的原始宽度和高度(然后相应地调整其大小),我使用以下方法:Javascript 图像上传测量的闭包问题,javascript,file,upload,closures,onload,Javascript,File,Upload,Closures,Onload,为了在上传时检查上传的img的原始宽度和高度(然后相应地调整其大小),我使用以下方法: var reader = new FileReader(); //Initiate the JavaScript Image object. var image = new Image(0,0); //Read the contents of Image File. reader.readAsDataURL(fileUpload.files[0]); reader.onload = function ()
var reader = new FileReader();
//Initiate the JavaScript Image object.
var image = new Image(0,0);
//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function () {
//Set the Base64 string return from FileReader as source.
image.src = this.result;
//Validate the File Height and Width.
image.onload = function () {
var height = this.naturalHeight;
var width = this.naturalWidth;
if (height > 100 || width > 100) {
// Do needed transformation
}
};
};
好的,到目前为止还不错。但现在,当我将此更改为多个文件上载的迭代时,如下所示:
for ( var i = 0; i < fileUpload.files.length; i++ ) {
var reader = new FileReader();
//Initiate the JavaScript Image object.
var image = new Image(0,0);
var iteratedFile = fileUpload.files[i];
//Read the contents of Image File.
reader.readAsDataURL(iteratedFile);
reader.onload = function () {
//Set the Base64 string return from FileReader as source.
image.src = this.result;
//Validate the File Height and Width.
image.onload = function () {
var height = this.naturalHeight;
var width = this.naturalWidth;
if (height > 100 || width > 100) {
// Fails to do anything related to i; i is undefined here, returns undefined too
console.log( fileUpload.files[i] );
// Returns the last iterated name
console.log( iteratedFile );
}
};
};
}
for(var i=0;i100 | |宽度>100){
//无法执行与i相关的任何操作;此处i未定义,返回未定义
log(fileUpload.files[i]);
//返回上次迭代的名称
log(iteratedFile);
}
};
};
}
我无法访问内部侦听器中的迭代文件。怎么会?
当我在写它的地方写console.log(iteratedFile)
时,我实际上总是得到最后一个迭代文件的名称,这让我注意到这是一个闭包问题。然而,当我写console.log(I)时
或console.log(fileUpload.files[i])
在同一个地方,而不是在那一行,我得到了未定义的
,我真的不明白。如何使迭代文件在最内部的作用域中可用(访问其名称、mime等)
更新
将
(i)
添加到reader.onload函数的函数定义末尾;我现在可以console.log在所有三次迭代的外部函数中输入正确的I值,但随后会将get
request 404错误发送到控制台中显示的pages\u URL/undefined
。什么 将i
的词汇环境范围限定到循环内部调用的IIFE实际上足以使其像一个符咒一样工作:
for ( var i = 0; i < fileUpload.files.length; i++ ) {
(function(){
var reader = new FileReader();
//Initiate the JavaScript Image object.
var image = new Image(0,0);
var iteratedFile = fileUpload.files[i];
//Read the contents of Image File.
reader.readAsDataURL(iteratedFile);
reader.onload = function () {
//Set the Base64 string return from FileReader as source.
image.src = this.result;
//Validate the File Height and Width.
image.onload = function () {
var height = this.naturalHeight;
var width = this.naturalWidth;
if (height > 100 || width > 100) {
// Works now
console.log( fileUpload.files[i] );
// Returns the iterated file
console.log( iteratedFile );
}
};
};
}());
}
for(var i=0;i100 | |宽度>100){
//现在工作
log(fileUpload.files[i]);
//返回迭代文件
log(iteratedFile);
}
};
};
}());
}