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

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

下面是我用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

  }

 }

})

})

})

如果有文件名的话,我能想到的就是用个正则判断文件扩展名是不是符合

function isVDOType(s) {

var patrn = /\w+(.flv|.rvmb|.mp4|.avi|.wmv)$/

if (!patrn.exec(s)) return false

return true

}

文件类型修改到需要的集合


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11594972.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存