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();" />
#1 Jhoee says:
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.