Html 如何在单击“文件上载”时仅显示pdf、doc、docx格式

Html 如何在单击“文件上载”时仅显示pdf、doc、docx格式,html,input,Html,Input,我试图用我的代码阻止除doc、docx和pdf之外的所有扩展,就像只接受googlechrome 这是我的代码: <input type="file" id="filedocxpdf" name="filedocxpdf" class="txtNotice" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"/&

我试图用我的代码阻止除doc、docx和pdf之外的所有扩展,就像只接受
googlechrome

这是我的代码:

<input type="file" id="filedocxpdf" name="filedocxpdf" class="txtNotice" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"/>

这可能会帮助你

Javascript解决方案

var myfile="";

$('#button_id').click(function( e ) {
    e.preventDefault();
    $('#filedocxpdf').trigger('click');
});

$('#filedocxpdf').on( 'change', function() {
   myfile= $( this ).val();
   var ext = myfile.split('.').pop();
   if(ext=="pdf" || ext=="docx" || ext=="doc"){
       alert(ext); return true;

   } else{
       alert(ext); return false;
   }
});
备选解决方案2

<script type="text/javascript" language="javascript">
function checkfile(sender) {
    var validExts = new Array(".docx", ".doc", ".pdf");
    var fileExt = sender.value;
    fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
    if (validExts.indexOf(fileExt) < 0) {
      alert("Invalid file selected, valid files are of " +
               validExts.toString() + " types.");
      return false;
    }
    else return true;
}
</script>

<input type="file" id="filedocxpdf" onchange="checkfile(this);" />

函数检查文件(发送方){
var validExts=新数组(“.docx”、“.doc”、“.pdf”);
var fileExt=sender.value;
fileExt=fileExt.substring(fileExt.lastIndexOf('.');
if(有效索引索引of(fileExt)<0){
警报(“选择的文件无效,有效文件为”+
toString()+“types.”);
返回false;
}
否则返回true;
}

其他浏览器忽略了这样一个accept属性,例如。 例如,Firefox支持一些简单的情况,比如accept=“image/gif”

您需要创建一个Javascript解决方案来检查文件扩展名:

var file = document.getElementById('someId');

file.onchange = function(e){
    var ext = this.value.match(/\.([^\.]+)$/)[1];
    switch(ext)
    {
        case 'jpg':
        case 'bmp':
        case 'png':
        case 'tif':
            alert('allowed');
            break;
        default:
            alert('not allowed');
            this.value='';
    }
};
范例