Search code examples
javascriptfunctionfileinputis-empty

Input file does not run function if empty


If I insert png it works, if I insert jpg it works, but if I leave the file empty it doesn't work, why? The file should be png or empty.

function myFunction() {
  var fileTypecheck = document.getElementById("file").files[0].type.replace(/(.*)\//g, '');
  
  if(fileTypecheck == "png" || fileTypecheck.length == 0){
  
      alert("File is png or 0");
  }else{
      alert("File is NOT png or 0");
  }
}
<input type="file" name="file" id="file"  onchange="loadFile(event)" accept="image/png">

<button onclick="myFunction()">Click me</button>


Solution

  • When an <input type="file"/> has no files selected its HTMLInputElement.files property is empty, so files[0] is undefined.

    BTW, you should not rely on the browser to always accurately tell you of a file's type: browsers typically populate the File.type property from their host OS's file-extension-to-MIME-type registry which is not reliable and often outdated.

    That said, change your code to this: note that I've added defensive programming steps to actually verify things instead of making assumptions:

    function myFunction() {
    
        const inp = document.getElementById("file");
        if( !inp || inp.type !== 'file' ) throw new Error( "'file' input element not found." );
        
        if( inp.files.length !== 1 ) {
            alert( "Please select a single file first." );
            return;
        }
    
        const file = inp.files[0];
        if( file.type === 'image/png' ) {
            // OK
        
        }
        else {
            alert( "Please select a PNG file." );
        }
    }