Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

FileUpload - Filter File Type/File Extension/File Size

, , , 9 Jan 2014
Rate this:
Please Sign up or sign in to vote.
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"; 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Authors

adriancs
Software Developer
Malaysia Malaysia
Writing programs is an art.

Vishal Pand3y
Software Developer
India India
No Biography provided

Wombaticus

United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
AnswerIE issue resolved Pinmember~~Atul~~25-Sep-14 21:12 
GeneralGood one Pinmvpthatraja8-Jan-14 1:57 
QuestionA general alternative [modified] PinmemberWombaticus5-Jan-14 1:59 
AnswerRe: A general alternative Pinmemberadriancs7-Jan-14 23:09 
GeneralRe: A general alternative PinmemberWombaticus7-Jan-14 23:15 
QuestionNice! PinmemberVolynsky Alex23-Dec-13 9:25 
GeneralMy vote of 5 Pinmemberpdsulliv23-Dec-13 3:27 
GeneralMy vote of 3 PinmemberVishal Pand3y23-Dec-13 1:22 
GeneralRe: My vote of 3 Pinmvpadriancs23-Dec-13 15:22 
GeneralRe: My vote of 3 PinmemberVishal Pand3y23-Dec-13 18:52 
GeneralRe: My vote of 3 Pinmemberadriancs3-Jan-14 19:07 
GeneralTry This too PinmemberVishal Pand3y9-Jan-14 19:22 
GeneralRe: Try This too Pinmemberadriancs9-Jan-14 20:06 
GeneralRe: Try This too Pinmemberadriancs9-Jan-14 20:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 10 Jan 2014
Article Copyright 2013 by adriancs, Vishal Pand3y, Wombaticus
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid