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;
}当用户单击submit按钮时,表单有一个file,然后我的checkform检查id名称onsubmit="return chkform();"是否为空。
如果没有,则调用函数displayPreview()。在这个函数中,我检查大小是否不超过50,宽度和高度是否等于width="181px"和height="181px"。
我正在返回ret,通过它我可以得到它返回的是真还是假的信息,但是在我的checkform中,我得到了checkform为什么?
编辑
在JSFIddle:bhardwaj/zaukV/添加了再现代码
发布于 2014-04-30 14:29:03
对不起,我没有使用您的代码,但这是您获得文件大小的方法。在此之后,很容易进行验证。如果文件大小不正确,还可以禁用或隐藏submit/upload按钮:
联署材料:
$("input:file").change(function () {
if ($(this).val() !== "") {
var file = $('#file_select')[0].files[0];
console.log(file.size);
}
});HTML:
<input type="file" name="file" id="file_select" />我还添加了一些获取宽度和预览图像的内容:http://jsfiddle.net/rq8nA/1/
https://stackoverflow.com/questions/23367031
复制相似问题