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


当前回答

你实际上可以用javascript来做,但记住js是客户端,所以你实际上是“警告用户”他们可以上传什么类型的文件,如果你想避免(限制或限制如你所说)某些类型的文件,你必须在服务器端做它。

如果您想开始服务器端验证,请查看这个基本的tut。对于整个教程,请访问这个页面。

好运!

其他回答

输入标记有accept属性。然而,它在任何方面都不可靠。 浏览器很可能将其视为“建议”,这意味着用户将根据文件管理器的不同,有一个只显示所需类型的预选。他们仍然可以选择“所有文件”,上传任何他们想要的文件。

例如:

<form> <输入类型=“文件” 名称=“图片” id=“图片” 接受=“图像/gif, 图像/jpeg” /> </form>

在HTML5规范中阅读更多

请记住,它只是用于“帮助”用户找到正确的文件。 每个用户都可以向您的服务器发送任何请求。 您总是需要验证服务器端的所有内容。

所以答案是:不,你不能限制,但你可以设置一个预选,但你不能依赖它。

Alternatively or additionally you can do something similar by checking the filename (value of the input field) with JavaScript, but this is nonsense because it provides no protection and also does not ease the selection for the user. It only potentially tricks a webmaster into thinking he/she is protected and opens a security hole. It can be a pain in the ass for users that have alternative file extensions (for example jpeg instead of jpg), uppercase, or no file extensions whatsoever (as is common on Linux systems).

你实际上可以用javascript来做,但记住js是客户端,所以你实际上是“警告用户”他们可以上传什么类型的文件,如果你想避免(限制或限制如你所说)某些类型的文件,你必须在服务器端做它。

如果您想开始服务器端验证,请查看这个基本的tut。对于整个教程,请访问这个页面。

好运!

是的,你说得对。这在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>

我的建议如下:

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

我知道有点晚了。

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;
}