html5 file accept属性详解

  html5的file控件新增accept属性,可以让弹出窗口显示允许mime类型的文件,而不是全部文件类型。

  在W3C的规格只允许Image/*Video/*Audio/*三种MIMEtype是允许的,也就是说上述三种以外的选择,就只能选择所有档案*.*

  DEMO

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
    <div>All Files <input type='file'></div>
    <div>Images <input type='file' accept='image/*'></div>
    <div>Videos <input type='file' accept='video/*'></div>
    <div>Audios <input type='file' accept='audio/*'></div>
    <div>Zip Files <input type='file' accept='.zip'></div>
    <div>Custom <input type='file' accept='.zip,.rar,.7z'></div>
</body>
</html>

第一个是使用了最基本的,也就是没有任何的限制

第二到第四个则是使用HTML5的规范内的MIMEtype

第五个则是限制只能上传.zip结尾的ZIP档

最后一个,则是同时允许.zip, .rar.7z三种格式

透过这样的范例,就知道怎么去限制不同类型的档案

如果想要支援所有影片档案、还有自订格式的话,就可以变成

<input type='file' accept='image/*,.exe'>

不过这边要特别注意一点,即便前端已经限制住了,后端也一定要检查,使用者传来的资料永远都是不可信的!

至于浏览器相容性的部分,IE10+

第五和第六种以及最后介绍的混合的都是非W3C规范内的所以FireFox不支持(实测firefox39+支持直接后缀形式)

 

补充:webkit核心浏览器,如chrome,及IE10+浏览器,选择rar文件竟然没有type属性,设置accept为application/rar,或者application/x-rar-compressed此种类型的mime也无法显示rar文件。不过可以增加后缀形式.rar,chrome39支持此种形式accept,选择文件窗口出现rar文件。firefox下rar文件type属性为application/rar则没有问题。

firefox下如果accept设置为application/x-rar-compressed,会导致accpet失效,等价于*.*,不懂什么问题。。。

来源:http://shinychang.net/article/53ff169465dd204503e125ad

加支付宝好友偷能量挖...


评论(0)网络
阅读(1455)喜欢(1)HTML/CSS兼容/XML