我正在开发 MVC 5 项目,我正在尝试裁剪和验证图像宽度和高度。
此处 jQuery 代码,reader.readAsDataURL(this.files[0])
发生错误“无法读取未定义的属性“0””。
var imageCropWidth = 0;
var imageCropHeight = 0;
var cropPointX = 0;
var cropPointY = 0;
var _URL = window.URL || window.webkitURL;
$('#files').change(function () {
debugger
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
if (this.width <= 200 && this.height <= 200) {
var reader = new FileReader();
reader.onload = function (e) {
// get loaded data and render thumbnail.
document.getElementById("image").src = e.target.result;
var jcrop_api = $('#image').Jcrop({
setSelect: [500, 500, 10, 10],
allowMove: true,
allowResize: false,
onChange: setCoordsAndImgSize,
boxWidth: 500,
boxHeight: 500
//onSelect: updatePreview
});
//jcrop_api.setOption({ allowMove: false });
//jcrop_api.setOption({ allowResize: false })
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
loadPopup();
}
else {
//$("#txtfileTitle").attr("placeholder", "Upload Image");
var message = "Image should be maximum 200x200 pixel size.";
errormesssage(message);
return false;
}
};
img.src = _URL.createObjectURL(file);
}
});
如何解决这个错误?
而且, 这是在裁剪之前或之后验证图像宽度和高度的好方法吗?
最佳答案
“无法读取未定义的属性“0””是因为您正在尝试访问数组"file"的元素“0”,即 null
或undefined
。您应该首先确定为什么您正在使用的"file"在您的代码期望它被实例化并从那里工作时没有被实例化。
尝试使用网络浏览器中的网络开发人员工具在 if ((file = this.files[0]))
上放置一个断点线,然后检查事物以了解原因 files
未定义。
一旦你完成了这个任务,就可以继续你的裁剪任务。
您的线路:if (this.width <= 200 && this.height <= 200)
可能是也可能不是检查图像大小的有效方法。尝试使用 jQuery 来获取对图像对象的引用,使用解释的内容 here .
祝你好运!
关于jquery - 如何解决 'cannot read property ' 0' of undefined'错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43751180/