Javascript 使用大小、高度和宽度验证图像上载
当用户单击提交按钮时,表单有一个Javascript 使用大小、高度和宽度验证图像上载,javascript,jquery,Javascript,Jquery,当用户单击提交按钮时,表单有一个onsubmit=“return chkform();”,然后我的checkform检查id名称文件是否为空 如果没有,则调用函数displayPreview()。在该函数中,我检查大小是否不超过50,宽度和高度是否不等于width=“181px”和height=“181px” 我返回ret,通过它我可以得到返回的信息是真是假 但是在我的检查表中,我得到了未定义的。。。为什么? 编辑 在JSFIddle添加了复制代码:很抱歉,我没有使用您的代码,但这是获得文件大小
onsubmit=“return chkform();”
,然后我的checkform
检查id名称文件是否为空
如果没有,则调用函数displayPreview()
。在该函数中,我检查大小是否不超过50,宽度和高度是否不等于width=“181px”
和height=“181px”
我返回ret,通过它我可以得到返回的信息是真是假
但是在我的检查表中,我得到了未定义的
。。。为什么?
编辑
在JSFIddle添加了复制代码:很抱歉,我没有使用您的代码,但这是获得文件大小的方法。之后就很容易验证了。如果文件大小不正确,您还可以禁用或隐藏“提交/上载”按钮:
JS:
HTML:
我还添加了一些内容以获得宽度和预览图像:
函数displayPreview不返回值。
function displayPreview(files) {
var reader = new FileReader();
var img = new Image();
reader.onload = function (e) {
img.src = e.target.result;
fileSize = Math.round(files.size / 1024);
if(fileSize>50) {
ret1=false;
alert("File size is " + fileSize + " kb");
return ret1;
} else {
var ret1 = true;
return ret1;
}
img.onload = function () {
if(this.width!="181" && this.height!="181") {
ret1=false;
alert("width=" + this.width + " height=" + this.height);
return ret1;
} else {
var ret1 = true;
return ret1;
}
console.log("width=" + this.width + " height=" + this.height+"File size is " + fileSize + " kb");
};
};
reader.readAsDataURL(files);
}
function chkform() {
var ret = false;
if (document.getElementById("file").value === "") {
console.log("empty");
} else {
var file = document.getElementById("file").files[0];
var tt=displayPreview(file);
console.log(tt+"nis");
}
return ret;
}
$("input:file").change(function () {
if ($(this).val() !== "") {
var file = $('#file_select')[0].files[0];
console.log(file.size);
}
});
<input type="file" name="file" id="file_select" />