how to get file extension using javascript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sandeep thakur
    New Member
    • Dec 2010
    • 1

    how to get file extension using javascript

    Code:
    <html>
    <head>
    <script type="text/javascript" language="javascript">
    function valid(ele)
    {
      var file_name= ele.file.value;
      
      
      var file_array = file_name.split(".");
     
      var file_array1 = file_array[1].toLowerCase();   
      
     
      if (file_array1 == 'gif' || file_array1 == 'jpg' || file_array1 == 'jpeg',file_array1=='gif')
      {
    	return true;  
      }
      else {
    	  
    	   alert("Please Upload Valid Image File");
    	   ele.file.focus();
    	   return false;
      }	  
      
    }
    </script>
    
    </head>
    <body>
    
    <form name="form1" action="upload_file.php" method="post" enctype="multipart/form-data" onsubmit="return valid(this);">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file" /> 
    <br />
    <input type="submit" name="submit" value="Submit" />
    </form>
    
    </body>
    </html>
    Last edited by gits; Dec 12 '10, 08:31 AM. Reason: added code tags
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    line 14 is quite weird ... the following part:
    Code:
    file_array1 == 'jpeg',file_array1=='gif'
    will avoid to match 'jpeg' since the first 2 conditions are false and the comma-operator will force the execution of the 'gif' check again at last and so 'jpeg' will never match. just drop everything after the comma.

    it could be simply improved to add more filetypes when using a filetype-map like:
    Code:
    var ft = { 'gif': 1, 'jpg': 1, 'png': 1 };
    
    // now use a simple existence-check like:
    if (splittedFileType in ft) {
        // valid
    } else {
        // invalid
    }
    Last edited by gits; Apr 6 '11, 08:49 AM.

    Comment

    Working...