本文介绍了如何允许< input type =" file">只接受图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要上传一个图片文件。我正在使用 注意,这只能向浏览器提供一个提示,告诉用户要显示哪些文件类型,但这很容易规避,所以你应该始终在服务器上验证上传的文件。



它应该可以在IE 10+,Chrome,Firefox,Safari 6+,Opera 15+上运行,但对手机支持非常粗略(截至2015年)据报道,这实际上可能会阻止一些移动浏览器上传任何内容,因此请务必好好测试您的目标平台。

有关详细的浏览器支持,请参阅


I need to upload a file which is an image. I am using <input type="file">.

However, this accepts all types of files. I need only files with extensions such as .jpg, .gif etc.

How can I make the upload dialog allow selection of only image files?

解决方案

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

Or simply:

<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.

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.

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

这篇关于如何允许&lt; input type =&quot; file&quot;&gt;只接受图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 14:56