Validate image size before the image change

Get image size and type before upload.


(function ($) {
    $.fn.checkFileType = function (options) {
        var defaults = {
            allowedExtensions: [],
            success: function (element) { },
            error: function (element) { }
        };
        options = $.extend(defaults, options);

        return this.each(function () {

            $(this).on('change', function () {
                var value = $(this).val(),
                    file = value.toLowerCase(),
                    extension = file.substring(file.lastIndexOf('.') + 1);

                if ($.inArray(extension, options.allowedExtensions) == -1) {
                    options.error(this);
                    $(this).focus();
                } else {
                    options.success(this);
                }

            });

        });
    };

})(jQuery);

$(function () {
    $('input[type=file]').change(function (e) {
        if (typeof FileReader == "undefined") return true;
    });

    $('input[type=file]').checkFileType({
        allowedExtensions: ['jpg', 'jpeg','png'],
        success: function (element) {
            //alert('Success');
            GetFileSize(element);
        },
        error: function () {
            $('#btnSaveProfilePhoto').fadeOut();
            alert("Please select image file.");
        }
    });
    TelInputMask();
});

function GetFileSize(fileid) {
    try {
        var fileSize = 0;
        //for IE
        if ($.browser.msie) {
            //before making an object of ActiveXObject, 
            //please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filePath = $(fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in kb
            fileSize = fileSize / 1048576; //size in mb 
        }
            //for FF, Safari, Opeara and Others
        else {
            fileSize = $(fileid)[0].files[0].size //size in kb
            fileSize = fileSize / 1048576; //size in mb 
        }

        //alert(GetSize(fileSize));

        if (Math.round(fileSize) > 2) {
            alert("Please select an image that is less than 2mb.");
        }
        else {
            readURL(fileid);
        }
        //alert("Uploaded File Size is " + Math.round(fileSize) + " MB");
    } catch (e) {
        //alert("Error is :" + e);
    }
}

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('.image_upload_preview').attr('src', e.target.result);
            $('#btnSaveProfilePhoto').fadeIn();
            $('#removePhoto').hide();
        }
        reader.readAsDataURL(input.files[0]);
    }
}
Validate image size before the image change Validate image size before the image change Reviewed by Bhaumik Patel on 8:14 PM Rating: 5