如何使 < input type = “ file”/> 只接受这些类型?

我想我的上传器只允许这些类型:

  • Doc Docx.
  • Xls,xlsx.
  • Ppt,pptx.
  • 短信。
  • Pdf.
  • 图像类型。

我怎样才能做到这一点? 我应该在 accept属性中加入什么? 谢谢你的帮助。

编辑! ! !

我还有一件事要问。当弹出窗口出现用于选择文件时,在右下角有一个包含所有允许文件的下拉列表。对我来说,名单会很长。我看到在列表中,有一个选项称为 All Supported Types。我如何使它默认选择和消除所有其他选项?

我们会感激你的帮助的,谢谢。

286277 次浏览

As stated on w3schools:

audio/* - All sound files are accepted

video/* - All video files are accepted

image/* - All image files are accepted

MIME_type - A valid MIME type, with no parameters. Look at IANA MIME types for a complete list of standard MIME types

Use accept attribute with the MIME_type as values

<input type="file" accept="image/gif, image/jpeg" />

for image write this

<input type=file accept="image/*">

For other, You can use the accept attribute on your form to suggest to the browser to restrict certain types. However, you'll want to re-validate in your server-side code to make sure. Never trust what the client sends you

for powerpoint and pdf files:

<html>
<input type="file" placeholder="Do you have a .ppt?" name="pptfile" id="pptfile" accept="application/pdf,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/vnd.openxmlformats-officedocument.presentationml.presentation"/>
</html>

The value of the accept attribute is, as per HTML5 LC, a comma-separated list of items, each of which is a specific media type like ABC1, or a notation like ABC2 that refers to all ABC3 types, or a filename extension like .gif. IE 10+ and Chrome support all of these, whereas Firefox does not support the extensions. Thus, the safest way is to use media types and notations like image/*, in this case

<input type="file" name="foo" accept=
"application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint,
text/plain, application/pdf, image/*">

if I understand the intents correctly. Beware that browsers might not recognize the media type names exactly as specified in the authoritative registry, so some testing is needed.

Use Like below

<input type="file" accept=".xlsx,.xls,image/*,.doc, .docx,.ppt, .pptx,.txt,.pdf" />

IMPORTANT UPDATE:

Due to use of only application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint... allows only till 2003 MS products, and not newest. I've found this:

application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.slideshow, application/vnd.openxmlformats-officedocument.presentationml.presentation

And that includes the new ones. For other files, you can retrieve the MIME TYPE in your file by this way (pardon the lang)(in MIME list types, there aren't this ones):

enter image description here

You can select & copy the type of content