简体   繁体   English

验证图像上传的大小,高度和宽度

[英]Validate the image upload with size, height and width

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;
}

When a user clicks on the submit button, the form has an onsubmit="return chkform();" 当用户单击提交按钮时,表单有一个onsubmit="return chkform();" , then my checkform checks if the id name file is empty or not. ,然后我checkform检查ID名称file是否为空。

If not, then it call the function displayPreview() . 如果没有,则调用函数displayPreview() In that function I am checking whether the size is not more than 50 and width and height is not equal to width="181px" and height="181px" . 在该功能中,我正在检查尺寸是否不超过50,宽度和高度不等于width="181px"height="181px"

I am returning ret through which I can get the information it's returning true or false but In my checkform I am getting UNDEFINED ... why? 我返回RET,通过它我可以得到它的返回真或假,但在我的信息checkform我得到UNDEFINED ......为什么?

Edit 编辑

Added reproduction code at JSFIddle: http://jsfiddle.net/nishit_bhardwaj/zaukV/ 在JSFIddle添加了复制代码: http//jsfiddle.net/nishit_bhardwaj/zaukV/

Sorry I didn't work with your code but this is how you can get the filesize. 抱歉,我没有使用您的代码,但这是您获取文件大小的方法。 After that it's easy to validate. 之后,它很容易验证。 You also could disable or hide the submit/upload-button if the filesize is incorrect: 如果文件大小不正确,您还可以禁用或隐藏提交/上传按钮:

http://jsfiddle.net/rq8nA/ http://jsfiddle.net/rq8nA/

JS: JS:

$("input:file").change(function () {
       if ($(this).val() !== "") {
        var file = $('#file_select')[0].files[0];
        console.log(file.size);
       }
});

HTML: HTML:

<input type="file" name="file" id="file_select" />

I added something to get width and preview image too: http://jsfiddle.net/rq8nA/1/ 我添加了一些东西来获得宽度和预览图像: http//jsfiddle.net/rq8nA/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM