简体   繁体   中英

how to validate the photo upload not greater than 1MB from javascript

I am using asp.net and I have a html upload Control from where I have called the ValidatePhotographToUpload onChange event. I am not been able to validate.

My html code is as follows

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

My javascript code is as follows:

         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("");

        }
    }

when I upload photo of size 1.24mb I get 8 as a result. I take this Reference. but I didn`t get the result.

Any help are surely appretiated.

Check this example ; may be it will help you..

and a 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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