文件输入“接受"属性 - 有用吗? [英] File input 'accept' attribute - is it useful?

查看:27
本文介绍了文件输入“接受"属性 - 有用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Implementing a file upload under html is fairly simple, but I just noticed that there is an 'accept' attribute that can be added to the <input type="file" ...> tag.

这个属性作为限制文件上传到图像等的方式有用吗?使用它的最佳方式是什么?

Is this attribute useful as a way of limiting file uploads to images, etc? What is the best way to use it?

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

Alternatively, is there a way to limit file types, preferably in the file dialog, for an html file input tag?

推荐答案

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

The accept attribute is incredibly useful. It is a hint to browsers to only show files that are allowed for the current input. While it can typically be overridden by users, it helps narrow down the results for users by default, so they can get exactly what they're looking for without having to sift through a hundred different file types.

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

Note: These examples were written based on the current specification and may not actually work in all (or any) browsers. The specification may also change in the future, which could break these examples.

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>

accept 属性可以指定为用户代理提供提示将接受哪些文件类型.

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

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

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:

  • 表示接受声音文件.
  • 表示接受视频文件.
  • 表示接受图像文件.
  • 表示接受指定类型的文件.
  • 表示接受具有指定文件扩展名的文件.

这篇关于文件输入“接受"属性 - 有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆