check file extension before upload

Thursday 12th July 2007 05:25 PM

TAGS: javascript
For a web app, I wanted to run a quick check via javascript to make sure the file being uploaded was in the allowed file types (obviously this was hard-checked server side also), just to save the user some time and not need to process the whole form because of a simple filename mistake. Basic working example here.

<script type="text/javascript">

    function checkExtension()
    {
   
        // for mac/linux, else assume windows
        if (navigator.appVersion.indexOf('Mac') != -1 || navigator.appVersion.indexOf('Linux') != -1)
            var fileSplit = '/';
        else
            var fileSplit = '\\';
   
        var fileTypes     = new Array('.gif', '.jpg'); // valid filetypes
        var fileName      = document.getElementById('myInput').value; // current value
        var extension     = fileName.substr(fileName.lastIndexOf('.'), fileName.length);
        var valid = 0;
       
        for(var i in fileTypes)
        {
       
            if(fileTypes[i] == extension)
            {
           
                valid = 1;
                break;
               
            }
       
        }
       
        if(valid == 1)
            alert("Valid filetype, huzzah!");
        else
            alert("Do not collect 200 dollars!");
       
    }
   
</script>

<input type="file" id="myInput" />
<input type="button" value="Check File" onclick="checkExtension();" />

Comments on this article:


#1 Jhoee says:

Friday 29th February 2008 10:51 PM

hi! Thanks for sharing this. It help me on my current project and I am sure it will be of good use again someday. Thanks again.

#2 NateLiqGrav says:

Thursday 24th April 2008 04:45 AM

Note that this is case sensitive to extensions


Add Comment:


Make a Comment

*Nb, all comments are moderated to prevent spam or inappropriate content.








netforge logo
netforge provides high quality and friendly website design services to business. We're Australian based and reliable... (find out more).