如何从javascript验证不超过1MB的照片上传

时间:2014-04-01 11:52:27

标签: javascript jquery html asp.net file-upload

我正在使用asp.net,我有一个html上传控件,我调用了ValidatePhotographToUpload onChange事件。我无法验证。

我的HTML代码如下

     <input id="fupEventImage" type="file" size="45" name="LogoUploadedToUpload"                                           
      class="imguploader" onchange="return validatePhotographToUpload();" />

我的javascript代码如下:

         function ajaxFileUpload() {
        $("#FileLoading")
        .ajaxStart(function () {
            $(this).show();
        })
        .ajaxComplete(function () {
            $(this).hide();
        });
        $.ajaxFileUpload
        (
            {
                url: '<%=ResolveClientUrl("~/Handlers/AjaxFileUploader.ashx?PG=AddNewList&TY=L")%>',
                secureuri: false,
                fileElementId: 'fupEventImage',
                dataType: 'json',
                data: { name: 'logan', id: 'id' },
                success: function (data, status) {
                    if (typeof (data.error) != 'undefined') {
                        if (data.error != '') {
                            alert(data.error);
                        } else {
                            $('[id$=cropImageTarget]').attr('src', '<%= ResolveClientUrl("~/Handlers/DisplayUploadedImage.ashx?T=")%>' + new Date().getTime());
                            ShowThumbImage();
                            $("[id$=BodyContentPlaceHolder_ContentPlaceHolder1_btnClearImage2]").show();
                            $("#disablelayer").show();
                        }
                    }
                },
                error: function (data, status, e) {
                    alert(e);
                }
            }
        )
        return false;
    }
    function validatePhotographToUpload() {

        var uploadcontrol = $('[id$=fupEventImage]').val();
        var ext = uploadcontrol.substring(uploadcontrol.lastIndexOf('.') + 1);
        if (ext == 'jpg' || ext == 'jpeg' || ext == 'png' || ext == 'JPG' || ext == 'JPEG' || ext == 'PNG') {
            alert(uploadcontrol.length);
            alert((uploadcontrol.length / 1024) + 'KB');
            if (uploadcontrol.length <= 1048576) {
                ajaxFileUpload();
                $('[id$=LogoPhotoChangeHiddenField]').val('1');
            }
            else {
                jAlert("Warning!", "File Size is Very Large", "Maximum Allowed Size is 1MB.", "Red", false);
                $('[id$=fupEventImage]').val("");

            }
        }
        else {
            jAlert("Warning!", "Invalid Image Format", "Supported Format(jpg,jpeg,png)", "Red", false);
            $('[id$=fupEventImage]').val("");

        }
    }

当我上传大小为1.24mb的照片时,我得到8张照片。我参考了this。但我没有得到结果。

任何帮助肯定都是有用的。

1 个答案:

答案 0 :(得分:1)

检查这个例子;可能它会帮助你..

live example;

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function showFileSize() {
    var input, file;

    // (Can't use `typeof FileReader === "function"` because apparently
    // it comes back as "object" on some browsers. So just see if it's there
    // at all.)
    if (!window.FileReader) {
        bodyAppend("p", "The file API isn't supported on this browser yet.");
        return;
    }

    input = document.getElementById('fileinput');
    if (!input) {
        bodyAppend("p", "Um, couldn't find the fileinput element.");
    }
    else if (!input.files) {
        bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
    }
    else if (!input.files[0]) {
        bodyAppend("p", "Please select a file before clicking 'Load'");
    }
    else {
        file = input.files[0];
        bodyAppend("p", "File " + file.name + " is " + file.size + " bytes in size");
    }
}

function bodyAppend(tagName, innerHTML) {
    var elm;

    elm = document.createElement(tagName);
    elm.innerHTML = innerHTML;
    document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='showFileSize();'>
</form>
</body>
</html>