开发者

Showing only XML files in HTML file input element

开发者 https://www.devze.com 2023-03-27 18:27 出处:网络
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 :-

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 :-开发者_如何转开发\

(I'm checking this server side as well but would like to do it client side too)

Thanks


The answer is pretty simple, you use the MIME type. So if it is an xml file you want, you just do:

<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


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.

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

精彩评论

暂无评论...
验证码 换一张
取 消