input file,javascript, jquery判断文件类型,在input中设置accept属性只是好看,求两种代码,方便大家

百度答案是有,取value值,判断.后面的字符啊,正则表达式判断,神马神马的。求稍微标准有说服的答案。

下面是我用jquery写的选中后立马判断选中的文件的类型,不是的话提示,然后清除,对应的可以自己改成纯js形式:

 //文件上传文件选择后事件
 $(document).ready(function() {
  $("input[id^='fileToUpload']").each(
//这里是用了each因为是多文件上传,input的id都是fileToUpload  开头
    function() {
 $("#" + $(this).attr("id") + "").live('change',function() {
 var fileName = $(this).val();
 if (fileName != null&& 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) {
if (fileName.length > 100) {
 alert("文件名长度不能超过100字符");
 if (!window.addEventListener) {      
    document.getElementById(fileName[j]).outerHTML+='';  //IE清除inputfile
    }else { 
     document.getElementById(fileName[j]).value = "";   //FF清除inputfile
    } 
 return false;
}
return true;
 } else {
continue;
 }
 }
  alert("文件类型不合法,只支持 jpg、gif、png、jpeg类型!");
    if (!window.addEventListener) {      
    document.getElementById(fileName[j]).outerHTML+='';  //IE
    }else { 
     document.getElementById(fileName[j]).value = "";   //FF
    } 
   return false;
  } else {
   alert("文件类型不合法,只支持 jpg、gif、png、jpeg类型!");
    if (!window.addEventListener) {      
    document.getElementById(fileName[j]).outerHTML+='';  //IE
    }else { 
     document.getElementById(fileName[j]).value = "";   //FF
    } 
   return false;
  }
 }
});
});
});

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网