【问题标题】:Validate the image upload with size, height and width使用大小、高度和宽度验证图像上传
【发布时间】:2014-04-30 23:23:52
【问题描述】:
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;
}

当用户点击提交按钮时,表单有一个onsubmit="return chkform();",然后我的checkform检查id名称file是否为空。

如果不是,则调用函数displayPreview()。在该函数中,我正在检查大小是否不超过 50,宽度和高度是否不等于 width="181px"height="181px"

我正在返回 ret,通过它我可以获取它返回的信息是真还是假 但是在我的checkform 中,我收到了UNDEFINED...为什么?

编辑

在 JSFIddle 处添加重现代码:http://jsfiddle.net/nishit_bhardwaj/zaukV/

【问题讨论】:

  • 你的函数 displayPreview 没有返回值。

标签: javascript jquery


【解决方案1】:

抱歉,我没有使用您的代码,但这是您获取文件大小的方法。之后很容易验证。如果文件大小不正确,您也可以禁用或隐藏提交/上传按钮:

http://jsfiddle.net/rq8nA/

JS:

$("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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 2018-07-14
    • 2013-09-14
    • 1970-01-01
    • 2017-12-08
    相关资源
    最近更新 更多