我想限制可以从本机操作系统文件选择器中选择的文件类型,当用户单击HTML中的<input type="file">元素中的Browse按钮时。我感觉这是不可能的,但我想知道是否有解决办法。我希望只使用HTML和JavaScript;请不要用闪光灯。


当前回答

我知道有点晚了。

function Validatebodypanelbumper(theForm)
{
   var regexp;
   var extension =     theForm.FileUpload.value.substr(theForm.FileUpload1.value.lastIndexOf('.'));
   if ((extension.toLowerCase() != ".gif") &&
       (extension.toLowerCase() != ".jpg") &&
       (extension != ""))
   {
      alert("The \"FileUpload\" field contains an unapproved filename.");
      theForm.FileUpload1.focus();
      return false;
   }
   return true;
}

其他回答

使用带有accept属性的输入标记

<input type="file" name="my-image" id="image" accept="image/gif, image/jpeg, image/png" />

点击这里查看最新的浏览器兼容性表

现场演示在这里

如果只选择图像文件,可以使用accept="image/*"

<input type="file" name="my-image" id="image" accept="image/*" />

现场演示在这里

只有gif, jpg和png将显示,屏幕截图从Chrome 44版

是的,你说得对。这在HTML中是不可能的。用户将能够选择任何他/她想要的文件。

您可以编写一段JavaScript代码来避免根据扩展名提交文件。但请记住,这绝不能阻止恶意用户提交他/她真正想要的任何文件。

喜欢的东西:

function beforeSubmit()
{
    var fname = document.getElementById("ifile").value;
    // check if fname has the desired extension
    if (fname hasDesiredExtension) {
        return true;
    } else {
        return false;
    }
}

HTML代码:

<form method="post" onsubmit="return beforeSubmit();">
    <input type="file" id="ifile" name="ifile"/>
</form>

我知道有点晚了。

function Validatebodypanelbumper(theForm)
{
   var regexp;
   var extension =     theForm.FileUpload.value.substr(theForm.FileUpload1.value.lastIndexOf('.'));
   if ((extension.toLowerCase() != ".gif") &&
       (extension.toLowerCase() != ".jpg") &&
       (extension != ""))
   {
      alert("The \"FileUpload\" field contains an unapproved filename.");
      theForm.FileUpload1.focus();
      return false;
   }
   return true;
}

我的建议如下:

If you have to make user select any of image files by default, the use accept="image/*" <input type="file" accept="image/*" /> if you want to restrict to specific image types then use accept="image/bmp, image/jpeg, image/png" <input type="file" accept="image/bmp, image/jpeg, image/png" /> if you want to restrict to specific types then use accept=".bmp, .doc, .pdf" <input type="file" accept=".bmp, .doc, .pdf" /> You cannot restrict user to change file filer to all files, so always validate file type in script and server

您可以使用更改事件监视用户选择的内容,并在此时通知他们该文件不可接受。它没有限制实际显示的文件列表,但是除了不受支持的accept属性之外,它是最接近客户端的。

var file = document.getElementById('someId'); 文件。Onchange =函数(e) { Var ext = this.value.match(/\.([^\.]+)$/)[1]; Switch (ext) { 例“jpg”: 例“bmp”: 例“png”: 气管无名动脉瘘管的情况下“”: 警报(允许的); 打破; 默认值: 警报(“不允许”); 这一点。Value = "; } }; <input type="file" id="someId" />

JSFiddle