<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>JS判断上传图片格式是否正确</title> </head> <body> <input type="file" id="file"/> <input id="btn" type="button" value="button"/> <script> function isPicFile(fileName) { //lastIndexOf如果没有搜索到则返回为 -1 if (fileName.lastIndexOf(".") != -1) { var fileType = (fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)).toLowerCase(); var suppotFile = new Array(); suppotFile[0] = "jpg"; suppotFile[1] = "gif"; suppotFile[2] = "bmp"; suppotFile[3] = "png"; suppotFile[4] = "jpeg"; for ( var i = 0; i < suppotFile.length; i++) { if (suppotFile[i] == fileType) { return true; } else { continue; } } alert("文件类型不合法,只能是jpg、gif、bmp、png、jpeg、png类型!"); return false; } else { alert("文件类型不合法,只能是 jpg、gif、bmp、png、jpeg、png类型!"); return false; } } var oFile = document.getElementById('file'); var oBtn = document.getElementById('btn'); oBtn.onclick = function () { isPicFile( oFile.value ); }; </script> </body> </html>