Click here to Skip to main content
15,879,535 members
Articles / Web Development / ASP.NET
Tip/Trick

FileUpload - Filter File Type/File Extension/File Size

, ,
Rate me:
Please Sign up or sign in to vote.
4.76/5 (31 votes)
9 Jan 2014CPOL 105.6K   27   15
Sample JavaScript for filtering file extension and file size

Version 1

Check File Extension

JavaScript

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)

JavaScript
<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

JavaScript
<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.NET
<asp:FileUpload ID="FileUpload1" 
onchange="return CheckFile(this);" runat="server" /> 

or add it at code behind:

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

Version 2

JavaScript
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

ASP.NET
<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.NET
<asp:fileupload id="FileUpload1" CssClass="s" runat="server"></asp:fileupload>

or add it at code behind:

C#
FileUpload1.CssClass = "s";

License

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


Written By
Software Developer
Other Other
Programming is an art.

Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionError Pin
Walter Nuñez23-May-16 11:43
Walter Nuñez23-May-16 11:43 
AnswerIE issue resolved Pin
~~Atul~~25-Sep-14 21:12
~~Atul~~25-Sep-14 21:12 
GeneralGood one Pin
thatraja8-Jan-14 1:57
professionalthatraja8-Jan-14 1:57 
QuestionA general alternative Pin
Wombaticus5-Jan-14 1:59
Wombaticus5-Jan-14 1:59 
AnswerRe: A general alternative Pin
adriancs7-Jan-14 23:09
mvaadriancs7-Jan-14 23:09 
GeneralRe: A general alternative Pin
Wombaticus7-Jan-14 23:15
Wombaticus7-Jan-14 23:15 
QuestionNice! Pin
Volynsky Alex23-Dec-13 9:25
professionalVolynsky Alex23-Dec-13 9:25 
GeneralMy vote of 5 Pin
pdsulliv23-Dec-13 3:27
pdsulliv23-Dec-13 3:27 
GeneralMy vote of 3 Pin
Vishal Pand3y23-Dec-13 1:22
Vishal Pand3y23-Dec-13 1:22 
GeneralRe: My vote of 3 Pin
adriancs23-Dec-13 15:22
mvaadriancs23-Dec-13 15:22 
Cool, I have added your version into the tips Smile | :)
GeneralRe: My vote of 3 Pin
Vishal Pand3y23-Dec-13 18:52
Vishal Pand3y23-Dec-13 18:52 
GeneralRe: My vote of 3 Pin
adriancs3-Jan-14 19:07
mvaadriancs3-Jan-14 19:07 
GeneralTry This too Pin
Vishal Pand3y9-Jan-14 19:22
Vishal Pand3y9-Jan-14 19:22 
GeneralRe: Try This too Pin
adriancs9-Jan-14 20:06
mvaadriancs9-Jan-14 20:06 
GeneralRe: Try This too Pin
adriancs9-Jan-14 20:14
mvaadriancs9-Jan-14 20: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.