'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;
Hope someone can guide me which part I am getting wrong.
Solution 1:[1]
Try using the following solution
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 = name.split('.');
ext = ext[ext.length - 1];
alert("here is a file path: " + ext);
}
}
<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()" />
Solution 2:[2]
RegEx (Fast & Accurate) version of pathInfo:
function pathInfo(s) {
s=s.match(/(.*?\/)?(([^/]*?)(\.[^/.]+?)?)(?:[?#].*)?$/);
return {path:s[1],file:s[2],name:s[3],ext:s[4]};
}
var sample='folder/myfolder/another/file.min.js?query=1';
var result=pathInfo(sample);
console.log(result);
/*
{
"path": "folder/myfolder/another/",
"file": "file.min.js",
"name": "file.min",
"ext": ".js"
}
*/
console.log(result.ext);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lars Flieger |
| Solution 2 | MMMahdy-PAPION |


