Click here to Skip to main content
12,633,417 members (30,602 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

59.9K views
28 bookmarked
Posted

FileUpload - Filter File Type/File Extension/File Size

, , , 9 Jan 2014 CPOL
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

You may also be interested in...

Comments and Discussions

 
QuestionError Pin
Walter Nuñez23-May-16 12:43
memberWalter Nuñez23-May-16 12:43 
AnswerIE issue resolved Pin
~~Atul~~25-Sep-14 22:12
member~~Atul~~25-Sep-14 22:12 
GeneralGood one Pin
thatraja8-Jan-14 2:57
mvpthatraja8-Jan-14 2:57 
QuestionA general alternative Pin
Wombaticus5-Jan-14 2:59
memberWombaticus5-Jan-14 2:59 
AnswerRe: A general alternative Pin
adriancs8-Jan-14 0:09
memberadriancs8-Jan-14 0:09 
GeneralRe: A general alternative Pin
Wombaticus8-Jan-14 0:15
memberWombaticus8-Jan-14 0:15 
QuestionNice! Pin
Volynsky Alex23-Dec-13 10:25
memberVolynsky Alex23-Dec-13 10:25 
GeneralMy vote of 5 Pin
pdsulliv23-Dec-13 4:27
memberpdsulliv23-Dec-13 4:27 
GeneralMy vote of 3 Pin
Vishal Pand3y23-Dec-13 2:22
memberVishal Pand3y23-Dec-13 2:22 
GeneralRe: My vote of 3 Pin
adriancs23-Dec-13 16:22
mvpadriancs23-Dec-13 16:22 
GeneralRe: My vote of 3 Pin
Vishal Pand3y23-Dec-13 19:52
memberVishal Pand3y23-Dec-13 19:52 
GeneralRe: My vote of 3 Pin
adriancs3-Jan-14 20:07
memberadriancs3-Jan-14 20:07 
GeneralTry This too Pin
Vishal Pand3y9-Jan-14 20:22
memberVishal Pand3y9-Jan-14 20:22 
GeneralRe: Try This too Pin
adriancs9-Jan-14 21:06
memberadriancs9-Jan-14 21:06 
GeneralRe: Try This too Pin
adriancs9-Jan-14 21:14
memberadriancs9-Jan-14 21:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web02 | 2.8.161208.2 | Last Updated 10 Jan 2014
Article Copyright 2013 by adriancs, Vishal Pand3y, Wombaticus
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid