0

大家好,我如何使用javascript检查输入按钮中的多个文件扩展,例如文件必须是mp3,mp4

<p><input type="file" id="file" name="file" size="23"/></p><br />
        <p><input type="submit" value="Upload file" /></p> 

Javascript:

$(function () {
    $('form').submit(function () {
        var selectedFile = $('#file').val();
        var matches = selectedFile.match(/\.(xlsx?)$/i);
        if (matches == null) {
            alert('please select an Excel file');
            return false;
        }
        return true;
    });
});
4

2 回答 2

1

您可以使用正则表达式执行此操作:

filename.match(/\.mp[34]$/i);

子字符串:

if (filename.substr(-4) === '.mp3' || filename.substr(-4) === '.mp4')
{
    //do stuff
}

甚至split

var parts = filename.split('.');
switch(parts[parts.length -1])
{
    case 'mp3':
    case 'mp4':
        //do stuff
    break:
    case 'txt':
        //etc...
}
//or even:
if (filename.split('.mp').length > 1){}

而且indexOf,当然:

if (filename.indexOf('.mp') !== -1)
{
    //note, still need to check if it's mp>3< or mp>4<
}
于 2012-11-02T14:51:40.760 回答
1

尝试这个

var validFilesTypes = ["mp3", "mp4"];
function Validate(path) 
{        
 var ext = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
 var isValidFile = false;
 for (var i = 0; i < validFilesTypes.length; i++) 
 {
   if (ext == validFilesTypes[i]) 
   {
     isValidFile = true;
     break;
   }
 }
 if (!isValidFile) 
   alert('Please select file of mp3 and mp4 extension only.');             

 return isValidFile;
}
于 2012-11-02T14:40:22.610 回答