我需要验证一个具有所需宽度、高度的文件字段,如果文件没有使用 JavaScript 上传,但它不会像这样发生。这是我的代码:
<input type="file" name="copImage" id="copImage" class="form-control" value="" onchange="setBackgroundImage(event);">
function setBackgroundImage(e){
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
};
console.log('size bg',backImageHeight,backImageWidth);
}
在这里我无法获取文件height
和width
. 我还要检查文件是否没有上传。
将日志语句放入onload
函数内。这是因为您试图访问其范围之外的变量,否则在 onload 函数之外定义这些变量
bg.onload = function() {
var bgLoaded = true,
backImageHeight = this.height,
backImageWidth = this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
假设我有一个按钮并且没有选择文件,如果我点击文件警报应该说选择文件。
似乎您不能使用onchange
事件处理程序来做到这一点,因为如果未加载文件。什么都没有改变,所以函数不会触发。在这种情况下,您可以创建一个变量并在文件上传时更新其状态。单击按钮检查变量状态
var isFileLoaded = false;
function setBackgroundImage(fileValue) {
var url = URL.createObjectURL(fileValue.files[0]);
bg = new Image();
if (fileValue.value !== '') {
bg.src = url;
bg.onload = function() {
bgLoaded = true;
isFileLoaded = true;
backImageHeight = this.height;
backImageWidth = this.width;
console.log('size bg', backImageHeight, backImageWidth);
};
}
}
function buttonClick() {
if (isFileLoaded) {
} else {
alert('No file selected')
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句