Search code examples
javascriptfilefile-extension

Get the file extension in the JavaScript


I have a problem checking what is an extension in my multiple input files. I am added pathinfo in the javascript and alert to check the file extension, but cannot work. Below is my coding:

<!DOCTYPE html>
<html>
<body>



<input type="file" name="vasplus_multiple_files" id="vasplus_multiple_files"   accept="application/msword, application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/*" multiple="multiple"/>
    <input type="submit" name="next" class="action-button" value="Submit" onclick="sendFunc_web()"/> 
<script>
function sendFunc_web(){
                var inp = document.getElementById('vasplus_multiple_files');
                var count = inp.files.length;
                for (var i = 0; i < inp.files.length; ++i) {
                    var num = i+1;
                    var name = inp.files.item(i).name;      
                    var ext = pathinfo(name, PATHINFO_EXTENSION);   
                     alert("here is a file path: " + ext);
                                
                }

        }
</script>

</body>
</html>

For example, if the file names are abcdefg.pdf and haha.jpeg, I want to alert twice data to show extensions are pdf and jpeg``.

The result might be like below the pictures;

output 1

output 2

Hope someone can guide me which part I am getting wrong.


Solution

  • You can split the name file by dot, and access last index:

    function sendFunc_web() {
      var inp = document.getElementById('vasplus_multiple_files');
      var count = inp.files.length;
      for (var i = 0; i < inp.files.length; ++i) {
        var num = i + 1;
        var name = inp.files.item(i).name;
        console.log(name)
        let ext = ext[ext.length - 1]
        console.log(ext)
      }
    }