如何允许输入类型为“文件".只接受图像文件? [英] How to allow <input type="file"> to accept only image files?

查看:99
本文介绍了如何允许输入类型为“文件".只接受图像文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要通过<input type="file">标签上传图像文件.

I need to upload only image file through <input type="file"> tag.

现在,它接受所有文件类型.但是,我想将其限制为仅包含.jpg.gif等的特定图像文件扩展名.

Right now, it accepts all file types. But, I want to restrict it to only specific image file extensions which include .jpg, .gif etc.

如何实现此功能?

推荐答案

使用输入标签的 accept 属性.因此,仅接受PNG,JPEG和GIF,可以使用以下代码:

Use the accept attribute of the input tag. So to accept only PNGs, JPEGs and GIFs you can use the following code:

<input type="file" name="myImage" accept="image/x-png,image/gif,image/jpeg" />

或者简单地:

<input type="file" name="myImage" accept="image/*" />

请注意,这仅向浏览器提示要显示给用户的文件类型,但这很容易绕开,因此您还应该始终在服务器上验证上载的文件.

Note that this only provides a hint to the browser as to what file-types to display to the user, but this can be easily circumvented, so you should always validate the uploaded file on the server also.

它应该可以在IE 10 +,Chrome,Firefox,Safari 6 +,Opera 15+中使用,但是在移动设备上的支持非常粗略(截至2015年),并且据报道,这实际上可能会阻止某些移动浏览器在以下位置上载任何内容:所有这些,因此请确保正确测试您的目标平台.

It should work in IE 10+, Chrome, Firefox, Safari 6+, Opera 15+, but support is very sketchy on mobiles (as of 2015) and by some reports this may actually prevent some mobile browsers from uploading anything at all, so be sure to test your target platforms well.

有关浏览器的详细支持,请参见 http://caniuse.com/#feat=input-文件接受

For detailed browser support, see http://caniuse.com/#feat=input-file-accept

这篇关于如何允许输入类型为“文件".只接受图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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