gpt4 book ai didi

Javascript - 如果 boolean 值真不工作

转载 作者:行者123 更新时间:2023-11-30 11:38:02 25 4
gpt4 key购买 nike

所以,我创建了以下函数来检查用户上传的文件是1) 仅图像2) 大小小于 maxSize KB3) 尺寸小于 maxWidth 和 maxHeight

除了我检查尺寸的条件外,其他一切都工作正常。 dimensions 中的值确实是正确的值,但条件 if(dimensions) 即使在 dimensions=true 时也不会运行。

我做错了什么吗?

var maxThumbnailWidth = '1050';
var maxThumbnailHeight = '700';
var maxThumbnailSize = '60';


function imageFileChecks(file, type) // type here refers to either Image or Banner or Thumbnail
{
var maxSize;
var maxWidth;
var maxHeight;
var dimensions = false;
if (type == 'image') {
maxSize = maxImageSize;
maxWidth = maxImageWidth;
maxHeight = maxImageHeight;
}
if (type == 'banner') {
maxSize = maxBannerSize;
maxWidth = maxBannerWidth;
maxHeight = maxBannerHeight;
}
if (type == 'thumbnail') {
maxSize = maxThumbnailSize;
maxWidth = maxThumbnailWidth;
maxHeight = maxThumbnailHeight;
}

//First check file type.. Allow only images

if (file.type.match('image.*')) {
var size = (file.size / 1024).toFixed(0);
size = parseInt(size);
console.log('size is ' + size + ' and max size is ' + maxSize);
if (size <= maxSize) {

var img = new Image();
img.onload = function() {
var sizes = {
width: this.width,
height: this.height
};
URL.revokeObjectURL(this.src);

//console.log('onload sizes', sizes);
console.log('onload width sizes', sizes.width);
console.log('onload height sizes', sizes.height);
var width = parseInt(sizes.width);
var height = parseInt(sizes.height);
if (width <= maxWidth && height <= maxHeight) {
dimensions = true;
console.log('dimensions = ', dimensions);
}

}

var objectURL = URL.createObjectURL(file);
img.src = objectURL;

if (dimensions) {
alert('here in dimensions true');
sign_request(file, function(response) {
upload(file, response.signed_request, response.url, function() {
imageURL = response.url;
alert('all went well and image uploaded!');
return imageURL;
})
})
} else {
return errorMsg = 'Image dimensions not correct!';
}


} else {
return errorMsg = 'Image size not correct!';
}

} else {
return errorMsg = 'Image Type not correct!';
}
}
<div class="form-group">
<label class="col-md-6 col-xs-12 control-label">Thumbnail</label>
<div class="col-md-6 col-xs-12">
<input type="file" id="thumbnail" class="file" required>
<br>
</div>
</div>

<script type="text/javascript">
document.getElementById('thumbnail').onchange = function() {
var file = document.getElementById('thumbnail').files[0];
if (!file) {
console.log("ji");
return;
}
var type = 'thumbnail';
var thumbnailURL = imageFileChecks(file, type);


}
</script>

最佳答案

这似乎是一个异步问题——您的 if(dimensions)语句在您的 img.onload 之前运行函数完成,在这种情况下 dimensions将等于 false当你到达代码中的那个部分时,尽管 img.onload函数及其逻辑正确执行。

您可以尝试嵌套 if(dimensions) img.onload 中的条件功能。

关于Javascript - 如果 boolean 值真不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43673534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com