28

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

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

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

accept=".xml"

Hope it helps

Comments

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

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.