以下代码似乎随机产生了aImg.naturalWidth
图片的实际宽度或0
。是适用于Linux的Chrome 70.0.3538.67吗?
如果不是bug,如何使其正常工作(不返回0
)?
function handleImageFile(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (file.type != 'image/jpeg') continue;
var img = document.createElement("img");
img.file = file;
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
$('#newPictureContainer').css('display', 'block');
document.getElementById('newPicture').appendChild(img);
aImg.src = e.target.result;
if (aImg.naturalWidth >= 300 || aImg.naturalHeight >= 300) {
if (aImg.naturalWidth <= aImg.naturalHeight)
aImg.width = 300;
else
aImg.height = 300;
$('#selectPicture').css('display', 'none');
} else {
$('#selectPicture [type=file]').val("");
alert("The smallest side of the picture should be at least 300 pixels.");
}
};
})(img);
reader.readAsDataURL(file);
}
}
<div id="selectPicture" style="display:block">
<input type="file" name="imageUpload" onchange="handleImageFile(this.files)"/>
</div>
<div id="newPictureContainer" style="display:none">
<span id="newPicture"></span>
<img src="/include/javascript/israelinfo/multiuploader/images/cross-small.gif"
width="16" height="16" title="Удалить" alt="Delete" class="MUdelete"
onclick="closePicture()">
</div>
答案 0 :(得分:1)
@JᴀʏMᴇᴇ给出了答案:
我必须在图像.naturalWidth
的处理程序中访问onload
,而不是FileReader
之一。
我错误地认为在将data:
URL分配给.src
之后立即加载了图像。似乎并非如此。