如何解决图片上传测量的关闭问题
要在上传时检查上传的 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 () {
//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 );
}
};
};
}
我无法访问内部侦听器中的迭代文件。怎么来的?
当我在我写的地方写 console.log( iteratedFile )
时,我实际上总是得到最后一个迭代文件的名称,这让我实际上注意到这是一个闭包问题。但是,当我在同一个地方而不是那一行写 console.log( i );
或 console.log(fileUpload.files[i])
时,我得到 undefined
,我不太明白。如何使 i
/ 迭代文件在最内部范围内可用(以访问其名称、mime 等内容)?
更新
通过在(i)
的函数定义末尾添加reader.onload function
;我现在可以在所有三个迭代的外部函数中使用 console.log 记录 i 的正确值,但随后将 GET
请求 404 错误发送到控制台中显示的 pages_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 );
}
};
};
}());
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。