Search code examples
javascriptinput-type-file

Prevent file loading


I have <input type="file" onchange="isValidFile(this.value)" />.

function isValidFile(filename)
{
     if (getExtension(filename)!=srt)
     {
          //Don't load the file
     }
}

When you load a file the label of <input type="file" /> change to filename, this show that file is loaded/selected, I want if the file have wrong extension to not load it and leave the label blank. I tried to change the value but read here that its not possible for security reasons.


Solution

  • <form name="abc">
        <input type="file" onchange="isValidFile(this.value)"/>
    </form>
    
    <script>
        function isValidFile(filename) {
            if (getExtension(filename) != 'jpg') {
                document.forms['abc'].reset();
                alert("invalid Image");
            }
        }
        function getExtension(filename) {
            return filename.substring(filename.lastIndexOf('.') + 1);
        }
    </script>
    

    Try this