Showing only XML files in HTML file input element
Asked Answered
S

3

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 :-\

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

Thanks

Satrap answered 13/8, 2011 at 21:35 Comment(1)
Check out the answer to this other SO question [#1978634 [1]: #1978634Magdeburg
A
56

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

Aldwin answered 22/5, 2015 at 7:52 Comment(1)
Actually these days, at least in Chrome, use accept=".xml" to explicitly have an XML option. The text/xml option will allow XML, XSLT, XBL and XSL.Durga
C
0

This worked for me, just write the accept attribute as follows in the input:

accept=".xml"

Hope it helps

Casady answered 1/9, 2023 at 17:42 Comment(0)
P
-1

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>
Petroglyph answered 13/8, 2011 at 21:42 Comment(2)
yea, I know I can do this while submitting but I prefer to do so when a user browse for the file. I saw that image uploading sites restrict for images only but they are using flash to achieve it and I don't want to use flash :-\Satrap
Hm if you want to give an immidiate response to the user as he/she chooses a file you might be out of look with simply html/js, but at least you can give some feedback as the user chooses a file. I updated my answer with a snippet for demonstration. Here I simply set the field value to be empty if a file with wrong extension is chosen. You could probably implement some more visual effects to indicate an error.Petroglyph

© 2022 - 2024 — McMap. All rights reserved.