jQuery to Validate File Type and Size before Uploading through Asp.Net FileUpload Control

Introduction: In this article I have explained how to validate file type (i.e. file extension) and file size of the file or image while uploading through Asp.Net FileUpload control before actually uploading using jQuery.
jQuery to validate file type and size before upload through Asp.Net FileUpload Control
Description: It is very common requirement while working on asp.net project to upload image files e.g. jpg, jpeg, png, bmp, gif etc or document files e.g. pdf, doc, docx, xls, xlsx, txt, rtf etc.  I got the same requirement where user can upload files. But I have to restrict user to upload only certain type of files and of up to specified size.

This can be done both server side and client side. But to check the file type or size of file at server size through code, file must be first uploaded into server memory which is time consuming if the size of the file is large. So it will definitely degrade the performance of our application. To overcome this problem we can validate file type and size at client side using jQuery before actually uploading the file/image.

Implementation: Let’s create a demo page for demonstration purpose.

HTML Source

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .error {
            background-color: #d9534f;
            font-weight: 300;
            font-size: 12px;
            padding: 3px 6px 3px 6px;
            color: #fff;
            text-align: center;
            white-space: nowrap;
        }
    </style>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#FileUpload1").change(function () {
                // Get uploaded file extension
                var extension = $(this).val().split('.').pop().toLowerCase();
                // Create array with the files extensions that we wish to upload
                var validFileExtensions = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
         //Check file extension in the array.if -1 that means the file extension is not in the list. 
                if ($.inArray(extension, validFileExtensions) == -1) {
                    $('#spnDocMsg').text("Sorry!! Upload only jpg, jpeg, png, gif, bmp file").show();
                    // Clear fileuload control selected file
                    $(this).replaceWith($(this).val('').clone(true));
                    //Disable Submit Button
                    $('#btnSubmit').prop('disabled', true);
                }
                else {
                    // Check and restrict the file size to 32 KB.
                    if ($(this).get(0).files[0].size > (32768)) {
                        $('#spnDocMsg').text("Sorry!! Max allowed file size is 32 kb").show();                
                     // Clear fileuload control selected file
                        $(this).replaceWith($(this).val('').clone(true));
                        //Disable Submit Button
                        $('#btnSubmit').prop('disabled', true);
                    }
                    else {
                        //Clear and Hide message span
                        $('#spnDocMsg').text('').hide();
                        //Enable Submit Button
                        $('#btnSubmit').prop('disabled', false);
                    }
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <fieldset style="width: 350px">
                <legend>Validate File Size and Type before upload</legend>
                Upload File:
                <asp:FileUpload ID="FileUpload1" runat="server" /><br />
                <span id="spnDocMsg" class="error" style="display: none;"></span>
                <br />
                <asp:Button ID="btnSubmit" runat="server" Text="Submit" ClientIDMode="Static" />
            </fieldset>
        </div>
    </form>
</body>
</html>

Explanation:  User can now upload file of jpg, jpeg, png, gif, bmp type and up to 32 kb size. If user selects any other file or large file than the specified limit then appropriate message will be displayed to user and submit button will be disabled. When a valid file of up to specified size is uploaded then submit button will be enabled.

Note: I have restricted user to upload up to 32kb file. If you want to restrict the file size to 2 mb then replace 32768 with 1024*1024*2 in above jquery script.

Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.        
Previous
Next Post »

2 comments

Click here for comments
Unknown
admin
February 05, 2020 ×

How can this be implemented for multiple file upload?
Will be very happy if you can explain.

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..