Popular Posts

Friday, 10 January 2014

FileUpload Check Constraints File Type and File Extension and File Size

SIMPLE PROGRAM TO CHECK THE VARIOUS CONSTRAINT REQUIRED AT  FOR FILE UPLOAD


THE DESIGN PAGE:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>FILE UPLOAD FILTERS</title>
    <script src="jquery-1.9.1.min.js" type="text/javascript"></script>
    
    <script type="text/javascript">
        $(document).ready(function () {
             var validFilesTypes = ["bmp", "gif", "png", "jpg", "jpeg", "doc", "docx", "xls", "xlsx", "htm", "html", "rar", "zip", "txt", "pdf"];
            $('.s').change(function () {
                CheckExtension(this);
                validateFileSize(this);
            });
            function CheckExtension(e) {
                /*global document: false */
                var file = e;
                var path = file.value;
                var ext = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
                var isValidFile = false;
                for (var i = 0; i < validFilesTypes.length; i++) {
                    if (ext == validFilesTypes[i]) {
                        isValidFile = true;
                        break;
                    }
                }
                if (!isValidFile) {
                    e.value = null;
                    alert("Invalid File. Unknown Extension Of Tender Doc" + "Valid extensions are:\n\n" + validFilesTypes.join(", "));
                }
                return isValidFile;
            }
            function validateFileSize(e) {
                /*global document: false */
                var file = e;
                var fileSize = file.files[0].size;
                var isValidFile = false;
                if (fileSize !== 0 && fileSize <= 4194304) {
                    isValidFile = true;
                }
                if (!isValidFile) {
                    e.value = null;
                    alert("File Size Should be Greater than 0 and less than 4 mb");
                }
                return isValidFile;
            }
        });
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="SELECT THE FILE TO UPLOAD"></asp:Label>
        <asp:FileUpload ID="FileUpload1" CssClass="s" runat="server" />
    </div>
    </form>
</body>
</html>


No comments :

Post a Comment