user1559811 user1559811 - 4 months ago 14
Javascript Question

check all extensions from a multiple upload file input

I need to change this code so that the condition checks the file extensions of all the selected files from a multiple select file input, this code only checks for one. any way I can do this?

var file = document.getElementById('file');
var ext = file.value.substring(file.value.lastIndexOf('.') + 1);

if(ext!== "mp4" && ext!== "m4v" && ext!== "f4v") {
alert('not an accepted file extension');
return false;
}

<input id="file" name="uploaded[]" type="file" multiple />

Answer

Note I only bothered to get the last three characters of the string because you only have three letter file extensions. If you wanted you could use .split('.') to get an array of segments and choose the last element of that array.

var selection = document.getElementById('file');
for (var i=0; i<selection.files.length; i++) {
    var ext = selection.files[i].name.substr(-3);
    if(ext!== "mp4" && ext!== "m4v" && ext!== "fv4")  {
        alert('not an accepted file extension');
        return false;
    }
}