Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Monday, 2 March 2015

This is common requirement  to check the file size before uploading or to download files up to specific size ex. 1 mb, file with size more than 1 mb will not allowed to download. This can be done by using server side code or using javascript.

In this article I will  explain How to restrict uploading files larger than the maximum specified file size by validating the file size client side using JavaScript when selecting the image/file through asp.net fileupload control.
In this example, the maximum allowed file size is 1 mb (1024 kb). This value can be changed as per requirement.

Source Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>File size validation using JavaScript</title>
    <script type="text/javascript">
        function validateFileSize() {
            var uploadControl = document.getElementById('<%= FileUpload1.ClientID %>');
            if (uploadControl.files[0].size > 1048576) {
                document.getElementById('dvMsg').style.display = "block";
                return false;
            }
            else {
                document.getElementById('dvMsg').style.display = "none";
                return true;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <fieldset style="width:300px;">
    <legend><strong>Validate file/Image size before upload</strong></legend>
    <br /><br />
      <asp:FileUpload ID="FileUpload1" runat="server" onchange="validateFileSize();" />
        <div id="dvMsg" style="background-color:Red; color:White; width:190px; padding:3px; display:none;" >
        Maximum size allowed is 1 MB
        </div>   <br />
        <br />
    </fieldset>    
    </div>
    </form>
</body>

</html>

0 comments:

Post a Comment