html - 文件输入 'accept' 属性——有用吗?

标签 html filter cross-browser mime-types

在 html 下实现文件上传相当简单,但我只是注意到有一个 'accept' 属性可以添加到 <input type="file" ...>标记。

这个属性作为一种限制文件上传到图像等的方法有用吗?最好的使用方法是什么?

或者,有没有办法限制文件类型,最好是在文件对话框中,用于 html 文件输入标签?

最佳答案

accept 属性非常有用。它提示浏览器只显示当前 input 允许的文件。虽然它通常可以被用户覆盖,但默认情况下它有助于缩小用户的结果范围,因此他们可以准确地获得他们正在寻找的内容,而无需筛选一百种不同的文件类型。

用法

注意:这些示例是根据当前规范编写的,可能实际上并不适用于所有(或任何)浏览器。规范也可能在未来发生变化,这可能会破坏这些示例。

h1 { font-size: 1em; margin:1em 0; }
h1 ~ h1 { border-top: 1px solid #ccc; padding-top: 1em; }
<h1>Match all image files (image/*)</h1>
<p><label>image/* <input type="file" accept="image/*"></label></p>

<h1>Match all video files (video/*)</h1>
<p><label>video/* <input type="file" accept="video/*"></label></p>

<h1>Match all audio files (audio/*)</h1>
<p><label>audio/* <input type="file" accept="audio/*"></label></p>

<h1>Match all image files (image/*) and files with the extension ".someext"</h1>
<p><label>.someext,image/* <input type="file" accept=".someext,image/*"></label></p>

<h1>Match all image files (image/*) and video files (video/*)</h1>
<p><label>image/*,video/* <input type="file" accept="image/*,video/*"></label></p>

来自 HTML 规范 (source)

The accept attribute may be specified to provide user agents with a hint of what file types will be accepted.

If specified, the attribute must consist of a set of comma-separated tokens, each of which must be an ASCII case-insensitive match for one of the following:

The string audio/*

  • Indicates that sound files are accepted.

The string video/*

  • Indicates that video files are accepted.

The string image/*

  • Indicates that image files are accepted.

A valid MIME type with no parameters

  • Indicates that files of the specified type are accepted.

A string whose first character is a U+002E FULL STOP character (.)

  • Indicates that files with the specified file extension are accepted.

关于html - 文件输入 'accept' 属性——有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/181214/

相关文章:

jquery - WordPress Gallery Effect - 图像/帖子一张一张弹出

html - Bootstrap 粘性页脚但没有滚动内容

html - 导航样式帮助

html - 试图用流体尺寸填充垂直固定 div 旁边的剩余空间

javascript - 实现跨浏览器移动兼容性

javascript - 使用Array.filter后如何获取多个值?

apache-flex - 在 Sprite 中获取应用于 Flash Sprite 的滤镜范围

filter - 是否可以向 highcharts 添加过滤器?

html - 图像是分辨率的正确 CSS 尺寸,但无法在浏览器中正确显示

javascript - 如何跨浏览器显示相对绝对日期?