javascript 在 HTML 文件输入元素中仅显示 XML 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7053436/
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
Showing only XML files in HTML file input element
提问by Shai
How can I show only XML files in a file input element? I read about the "accept" attribute but also learned no browser actually support it. I found here some JS scripts but they didn't work well :-\
如何在文件输入元素中仅显示 XML 文件?我阅读了“接受”属性,但也了解到没有浏览器实际支持它。我在这里找到了一些 JS 脚本,但它们效果不佳:-\
(I'm checking this server side as well but would like to do it client side too)
(我也在检查这个服务器端,但也想在客户端做)
Thanks
谢谢
回答by lordHougs
The answer is pretty simple, you use the MIME type. So if it is an xml file you want, you just do:
答案很简单,您使用 MIME 类型。因此,如果它是您想要的 xml 文件,则只需执行以下操作:
<input type="file" accept="text/xml" />
If you want to see the full list of MIME types, check this site http://www.iana.org/assignments/media-types/media-types.xhtml
如果您想查看 MIME 类型的完整列表,请查看此站点http://www.iana.org/assignments/media-types/media-types.xhtml
回答by kjetilh
Not sure if you can do that, but at least you could use a callback function and check the input value for the .xml extension.
不确定您是否可以这样做,但至少您可以使用回调函数并检查 .xml 扩展名的输入值。
Snippet:
片段:
<script type="text/javascript">
function isXml(input)
{
var value = input.value;
var res = value.substr(value.lastIndexOf('.')) == '.xml';
if (!res) {
input.value = "";
}
return res;
}
</script>
<form method="post" action="">
<input type="file" name="myfile" id="myfile" onchange="return isXml(this)" />
<input type="submit" />
</form>