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


当前回答

使用带有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;
}

使用带有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中的file属性上使用accept标记非常方便。

至于验证,我们必须在服务器端进行。我们也可以在js的客户端这样做,但这不是一个万无一失的解决方案。我们必须在服务器端进行验证。

对于这些需求,我真的更喜欢struts2 Java web应用程序开发框架。通过其内置的文件上传功能,将文件上传到基于struts2的web应用程序中是小菜一碟。只要提到我们希望在应用程序中接受的文件格式,其余的都由框架本身的核心处理。您可以在struts的官方网站上查看它。

我的建议如下:

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