Sunday, 9 November 2014

Validate File format and Size in ASP.NET using JAVASCRIPT

In this article, i am going to show how to valid file type and size of the file upload control in asp.net using JavaScript.


JavaScript Function

  <script type="text/javascript">
        // allowed file formats
        var validFilesType = ["bmp", "gif", "png", "jpg", "jpeg"];
        function ValidateFileTypeWithSize() {
            var fluploadImage = document.getElementById("<%=fluploadImage.ClientID%>");
            var lblMsg = document.getElementById("<%=lblMsg.ClientID%>");
            lblMsg.style.color = "red";
            lblMsg.innerHTML = '';
            var path = fluploadImage.value;
            // to get file extenstion like bmp, gif etc.
            var extension = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
            var isValidFile = false;
            for (var i = 0; i < validFilesType.length; i++) {
                if (extension == validFilesType[i]) {
                    isValidFile = true;
                    // mention maximum size 
                    if (fluploadImage.files[0].size > 4194304) {
                        fluploadImage.value = ''; // to clear fileuploader content
                        lblMsg.innerHTML = "Each image file can't exceed 4 MB";
                    }
                    break;
                }
            }

            // execute only in case of any file format which was not mentioned in 'validFilesType' variable
            if (!isValidFile) {
                fluploadImage.value = ''; // to clear fileuploader content
                lblMsg.innerHTML = "File Not Valid. Please upload a File with" +
                 " extension:\n\n" + validFilesType.join(", ");
            }
            return isValidFile;
        }
    </script>


Controls

  <asp:FileUpload ID="fluploadImage" onchange="ValidateFileTypeWithSize()" runat="server" />
            <asp:Label ID="lblMsg" runat="server"></asp:Label>
Output


That’s it!!…..Happy Programming...

No comments:

Post a Comment