小编典典

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

html

在html下实现文件上传非常简单,但我只是注意到可以将“ accept”属性添加到<input type="file" ...>标记中。

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

或者,是否有一种方法可以限制html文件输入标签的文件类型,最好在文件对话框中?


阅读 597

收藏
2020-05-10

共1个答案

小编典典

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规范源

accept可以指定该属性以向用户代理提示将接受哪种文件类型。

如果指定,则该属性必须由一 组逗号分隔的标记组成,每个标记都必须是以下其中一个的 ASCII不区分大小写的 匹配项:

字符串 audio/*

  • 表示接受声音文件。

字符串 video/*

  • 表示视频文件被接受。

字符串 image/*

  • 表示接受图像文件。

一个有效的MIME类型不带参数

  • 表示接受指定类型的文件。

一个字符串,其第一个字符为U + 002E FULL STOP字符(。)

  • 表示接受具有指定文件扩展名的文件。
2020-05-10