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