65.9K
CodeProject is changing. Read more.
Home

FileUpload - Filter File Type/File Extension/File Size

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.76/5 (31 votes)

Dec 22, 2013

CPOL
viewsIcon

107814

Sample JavaScript for filtering file extension and file size

Version 1

Check File Extension

JavaScript

<script type="text/javascript">
    var validFilesTypes = ["bmp", "gif", "png", "jpg", "jpeg", 
    "doc", "docx", "xls", "xlsx", "rar", "zip", "txt", "pdf"];

    function CheckExtension(file) {
        /*global document: false */
        var filePath = file.value;
        var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
        var isValidFile = false;

        for (var i = 0; i < validFilesTypes.length; i++) {
            if (ext == validFilesTypes[i]) {
                isValidFile = true;
                break;
            }
        }

        if (!isValidFile) {
            file.value = null;
            alert("Invalid File. Valid extensions are:\n\n" + validFilesTypes.join(", "));
        }

        return isValidFile;
    }
</script>

Check File Size

JavaScript (Note: This does not work on Internet Explorer)

<script type="text/javascript">
    var validFileSize = 15 * 1024 * 1024;

    function CheckFileSize(file) {
        /*global document: false */
        var fileSize = file.files[0].size;
        var isValidFile = false;
        if (fileSize !== 0 && fileSize <= validFileSize) {
            isValidFile = true;
        }
        else {
            file.value = null;
            alert("File Size Should be Greater than 0 and less than 15 MB.");
        }
        return isValidFile;
    }
</script>

Combine Both Functions

<script type="text/javascript">
    function CheckFile(file) {
        var isValidFile = CheckExtension(file);

        if (isValidFile)
            isValidFile = CheckFileSize(file);

        return isValidFile;
    }
</script>

Finally, add the event of onchange="return CheckFile(this);" into the ASP.NET FileUpload's attributes:

<asp:FileUpload ID="FileUpload1" 
onchange="return CheckFile(this);" runat="server" /> 

or add it at code behind:

protected void Page_Load(object sender, EventArgs e)
{
    FileUpload1.Attributes.Add("onchange", "return CheckFile(this);");
}

Version 2

function CheckFile(what,mb,iLen,types) {
   // what  : always =this in calling function
   // mb    : max file size allowed in MB
   // iLen  : max length of filename allowed (excluding the extension); 0 means don't test for length
   // types : comma-delimited string of allowed file extensions
   // eg, call with onchange="checkFile(this,4,50,'doc,docx,pdf')"
   var msg = '';
   var source = what.value;
   var i = source.lastIndexOf('\\');s
   var j = source.lastIndexOf('.');
   var fName = source.substring(i + 1, j);
   var ext = source.substring(source.lastIndexOf(".") + 1 ,source.length).toLowerCase();
   var exts = types.split(',');
   var fileTypeAllowed = false;
   for (var k = 0; k < exts.length; k++) {
      if (ext == exts[k]) {
         fileTypeAllowed = true;
         break;
      }
   }
   if (fileTypeAllowed==true) {
      var regex = /^[A-Za-z0-9_ -]{1,1024}$/;
      if (!regex.test(fName)) {
         msg = 'The file name contains illegal characters\n  
         Please re-name the file using only alphanumeric characters, hyphens, spaces and underscores\n';
      }
   } else {
      msg = 'Please upload files of the following types only:\n  ' + types + '\n';
   }
   if ((iLen > 0) && (fName.length > iLen)) {
      msg += 'The file name is too long\n  Please restrict it to ' + iLen.toString() + ' characters.\n';
   }
   var fileSize = what.files[0].size;
   var iMax = mb * 1024 * 1024;
   if (!((fileSize > 0) && (fileSize <= iMax))) {
      msg += "The file size should be greater than 0 and less than " + mb.toString() + "MB\n";
   }
   if (!(msg=='')) {
      what.value = null;
      alert(msg + '\n' + fName + '.' + ext);
   }
}

Version 3

<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 <= 25214400) {
                    isValidFile = true;
                }
                if (!isValidFile) {
                    e.value = null;
                    alert("File Size Should be Greater than 0 and less than 25 mb");
                }
                return isValidFile;
            }
        });
    
    </script>

and call it like this:

<asp:fileupload id="FileUpload1" CssClass="s" runat="server"></asp:fileupload>

or add it at code behind:

 FileUpload1.CssClass = "s";