Html 如何在 HTML5 中验证仅允许在“input type="file"” JPG、GIF 或 PNG 中使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11097272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:07:33  来源:igfitidea点击:

How to validade in HTML5 to only allow in 'input type="file"' JPG, GIF or PNG?

regexhtml

提问by André

Possible Duplicate:
Limit file format when using <input type=“file”>?

可能的重复:
使用 <input type="file"> 时限制文件格式?

I need to use the HTML5 patternattribute to only allow JPG, GIF and PNG files in a <input type="file">element.

我需要使用 HTML5pattern属性来只允许<input type="file">元素中包含 JPG、GIF 和 PNG 文件。

I currently have this pattern, but it is not working:

我目前有这种模式,但它不起作用:

<input type="file" class="input-file" id="tbinstUploadFile0" name="tbinstUploadFile0" placeholder="Please insert an image file..." pattern="([^\s]+(\.(?i)(jpg|png|gif|bmp))$)">

This regex pattern is not compatible with HTML5? How can I test for valid HTML5 regex patterns?

此正则表达式模式与 HTML5 不兼容?如何测试有效的 HTML5 正则表达式模式?

Best Regards,

此致,

回答by kiranvj

Try something like

尝试类似的东西

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

Click here for the latest browser compatibility table

单击此处获取最新的浏览器兼容性表

Live demo here

现场演示在这里

To select only image files, you can use this accept="image/*"

要仅选择图像文件,您可以使用此 accept="image/*"

<input type="file" name="my-image" id="image" accept="image/*" />

Live demo here

现场演示在这里

Only gif, jpg and png will be shown, screen grab from Chrome version 44Only gif, jpg and png will be shown, screen grab from Chrome version 44

仅显示 gif、jpg 和 png,Chrome 版本 44 的屏幕抓取仅显示 gif、jpg 和 png,Chrome 版本 44 的屏幕抓取