如何让<input type="file"/>只接受这些类型?

问题描述 投票:0回答:8

我希望我的上传者只允许这些类型:

  • 文档,文档。
  • xls,xlsx。
  • ppt,pptx。
  • txt.
  • pdf.
  • 图像类型。

我怎样才能实现这个目标?我应该在

accept
属性中添加什么内容?感谢您的帮助。

编辑!!!

我还有一件事要问。当出现用于选择文件的弹出窗口时,在右下角,有一个包含所有允许文件的下拉列表。就我而言,这个清单会很长。我在列表中看到有一个名为

All Supported Types
的选项。我怎样才能让它默认选择并消除所有其他选项?

任何帮助将不胜感激。谢谢你。

html file-upload input
8个回答
188
投票

accept
属性的值,根据HTML5 LC,是一个以逗号分隔的项目列表,其中每个项目都是特定的媒体类型,如image/gif
,或者是像
image/*
这样的表示法,表示所有 
image
 类型,或类似 
.gif
 的文件扩展名。 IE 10+ 和 Chrome 支持所有这些扩展,而 Firefox 不支持这些扩展。因此,最安全的方法是使用
媒体类型和像image/*
这样的符号,在这种情况下

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

如果我正确理解了意图。请注意,浏览器可能无法完全识别权威注册表中指定的媒体类型名称,因此需要进行一些测试。


141
投票
像下面一样使用

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

14
投票
重要更新:

由于仅使用 application/msword、application/vnd.ms-excel、application/vnd.ms-powerpoint... 只允许 2003 年之前的 MS 产品,而不是最新产品。我发现了这个:

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

这包括新的。对于其他文件,您可以通过这种方式检索文件中的 MIME TYPE(请原谅语言)(在 MIME 列表类型中,没有这个):

您可以选择并复制内容类型


13
投票
使用带有 MIME_type 作为值的接受属性

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

9
投票
对于 powerpoint 和 pdf 文件:

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

6
投票

w3schools所述:

音频/* - 接受所有声音文件

video/* - 接受所有视频文件

image/* - 接受所有图像文件

MIME_type - 有效的 MIME 类型,不带参数。看看 IANA MIME 类型以获取标准 MIME 类型的完整列表


0
投票
这是根据扩展名划分的

MIME Type 格式的 完整列表

  • .doc
    :应用程序/msword
  • .docx
    :application/vnd.openxmlformats-officedocument.wordprocessingml.document
  • .json
    :应用程序/json
  • .txt
    :文本/纯文本
  • ...
示例:

<input type="file" accept='application/msword, text/plain' />


    


-2
投票
对于图像写这个

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

对于其他, 您可以使用表单上的 Accept 属性来建议浏览器限制某些类型。但是,您需要在服务器端代码中重新验证以确保这一点。永远不要相信客户发给你的东西

© www.soinside.com 2019 - 2024. All rights reserved.