Show Image Preview after Validating Image Size and Type Before Upload in Asp.net using JQuery

In this tutorial i am going to explain How to validate image type and image size of the file in asp.net using jquery before image uploading on the server.
Show Image Preview after Validating Image Size and Type Before Upload in Asp.net using JQuery

This is very common requirement while we are working on asp.net project to upload image files such as .jpg, .jpeg, .png, .bmp, .gif and etc.
I got the same requirement in my live project where admin of website can upload product images.
But I have to restrict admin/user to upload only certain type of image sand of up to specified size and type.

This task can be done both server side and client side.
But I want to give one advise if you check the file type or size of file at server side through code,  your file must be first uploaded into server  and it require more time so if the size of the file is large than it will definitely degrade the performance of your web application.
To overcome this kind of problem you should validate file type and size at client side using jQuery or JavaScript before actually uploading the image.

So, Let's Create One Web application for validate file and also show preview of image.

HTML Source Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .error {
            background-color#d9534f;
            font-weight400;
            font-size20px;
            padding4px 7px 4px 7px;
            color#fff;
            text-aligncenter;
            white-spacenowrap;
        }
    </style>
    <script src="http://code.jquery.com/jquery-1.11.3.js" type="text/javascript"></script>
    <script type="text/javascript">
        //This is the function which Validate image size before upload
        function validateTypeAndSize(uploadCtrl) {
            // This is for Get uploaded file extension
            var extension = $(uploadCtrl).val().split('.').pop().toLowerCase();
            // This is for Create array with the files extensions that we wish to upload
            var validFileExtensions = ['jpeg''jpg''png''bmp'];
            //This is for Check file extension in the array.if -1 that means the file extension is not in the list.
            if ($.inArray(extension, validFileExtensions) == -1) {
                $('#spnMessage').text("Sorry!! Upload only jpg, jpeg, png, bmp image").show();
                // This is for Clear fileuload control selected file
                $(uploadCtrl).replaceWith($(uploadCtrl).val('').clone(true));
                //This is for Disable Submit Button
                $('#btnSubmit').prop('disabled'true);
                //This is for Clear Image preview
                $('#imgPreview').prop('src''');
            }
            else {
                // This is for Check and restrict the file size to 32 KB.
                if ($(uploadCtrl).get(0).files[0].size > (32768)) {
                    $('#spnMessage').text("Sorry!! Max allowed image size is 32 kb").show();
                    // This is for Clear fileuload control selected file
                    $(uploadCtrl).replaceWith($(uploadCtrl).val('').clone(true));
                    //This is for Disable Submit Button
                    $('#btnSubmit').prop('disabled'true);
                    //This is for Clear Image preview
                    $('#imgPreview').prop('src''');
                }
                else {
                    //This is for Clear and Hide message span
                    $('#spnMessage').text('').hide();
                    //This is for Enable Submit Button
                    $('#btnSubmit').prop('disabled'false);
                    //This is for Preview Image if valid
                    previewImage(uploadCtrl);
                }
            }
        }
        //This is for Preview image before upload
        function previewImage(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#imgPreview')
                    .attr('src', e.target.result)
                    .width(200)
                    .height(150);
                };
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div style="text-align:center">
            <h1>File Upload Example</h1>
            <p>www.asppoint.com</p>
            <asp:Image ID="imgPreview" Height="150px" Width="200px" runat="server" ClientIDMode="Static" />
            <br />
            <br />
            <asp:FileUpload ID="FileUpload1" runat="server" BackColor="Silver" ForeColor="White" onchange="validateTypeAndSize(this)" Height="27px" Width="239px" /><br />
            <br />
            <asp:Button ID="btnSubmit" BackColor="Green" ForeColor="White" runat="server" Text="Submit" Enabled="false" ClientIDMode="Static" Height="43px" Width="129px" /><p>
            <span id="spnMessage" class="error" style="displaynone;"></span></p>
            <br />
            <p>Designed & Developed by Nikunj Satasiya</p>
        </div>
    </form>
</body>
</html>

Now, User/Admin can now upload image file of .jpg, .jpeg, .png, .gif, .bmp type and up to 32 kb size if you require to change your file size than you can change in given jQuery as per your requirement.
If user selects any other file such as .zip, .rar and etc or large file than the specified limit then appropriate message will be displayed to user and submit button will be disabled.
When user choose valid file such as specified size is uploaded then submit button will be enabled and image preview will be shown in image box.

Previous
Next Post »

If you have any kind of question about any post, Feel free to ask.You can simply drop a comment below post. Your feedback and suggestions will be highly appreciated. ConversionConversion EmoticonEmoticon