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

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

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


当前回答

Chrome浏览器支持。它不应该用于验证,而是用于类型提示操作系统。如果在文件上传中有accept="image/jpeg"属性,操作系统只能显示建议类型的文件。

其他回答

Accept属性是在RFC 1867中引入的,目的是为文件选择控件启用基于MIME类型的文件类型过滤。但是到2008年为止,大多数(如果不是全部的话)浏览器都没有使用这个属性。使用客户端脚本,您可以为提交正确类型(扩展)的数据创建一种基于扩展的验证。

其他高级文件上传解决方案需要Flash电影(如SWFUpload)或Java applet(如JUpload)。

在2008年,由于缺少移动操作系统,这一点并不重要,但现在却非常重要。

当你设置可接受的mime类型时,例如,Android用户会得到系统对话框,应用程序可以为他提供文件输入接受的mime内容,这是很棒的,因为在移动设备上的文件资源管理器中浏览文件是缓慢的,经常有压力。

重要的一点是,一些移动浏览器(基于Android版本的Chrome 36和Chrome Beta 37)不支持应用程序对扩展和多种mime类型的过滤。

If the browser uses this attribute, it is only as an help for the user, so he won't upload a multi-megabyte file just to see it rejected by the server... Same for the <input type="hidden" name="MAX_FILE_SIZE" value="100000"> tag: if the browser uses it, it won't send the file but an error resulting in UPLOAD_ERR_FORM_SIZE (2) error in PHP (not sure how it is handled in other languages). Note these are helps for the user. Of course, the server must always check the type and size of the file on its end: it is easy to tamper with these values on the client side.

It's been a few years, and Chrome at least makes use of this attribute. This attribute is very useful from a usability standpoint as it will filter out the unnecessary files for the user, making their experience smoother. However, the user can still select "all files" from the type (or otherwise bypass the filter), thus you should always validate the file where it is actually used; If you're using it on the server, validate it there before using it. The user can always bypass any client-side scripting.

Chrome浏览器支持。它不应该用于验证,而是用于类型提示操作系统。如果在文件上传中有accept="image/jpeg"属性,操作系统只能显示建议类型的文件。