ccjmne
ccjmne

Reputation: 9606

How do I get a html5 file input to accept only certain file types consistently across browsers?

According to this answer on Stack Overflow, we can set the accept attribute of an <input type="file" /> to filter accepted input, as follows:

accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"

However, as you can notice running the simple snippet below, Chrome 43.0.something appears to simply disregard this configuration, while it is perfectly understood by Firefox 39.0.

I considered switching to a more blunt approach, using:

accept=".xls, .xlsx"

... which works fine in Chrome but makes Firefox somewhat confused, accepting only the files using the .xlsx extension.


Considering that this is probably very common and basic, I must be missing something: where am I screwing up? How do I get a html5 file input to suggest only .xls and .xlsx files consistently across browsers?

Here's a code snippet illustrating my issue (along with a JSFiddle link in case you'd wanna fiddle with it).

Accepts application/vnd.ms-excel and the likes:<br />
<label for="file1">File input</label>
<input type="file" name="file1" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
<hr />
Accepts .xls and .xlsx:<br />
<label for="file2">File input</label>
<input type="file" name="file2" accept=".xls, .xlsx"/>

Upvotes: 18

Views: 16702

Answers (4)

st0at
st0at

Reputation: 37

Remove space in

accept=".xls, .xlsx"

to

accept=".xls,.xlsx"

Works in Chrome 69 and Firefox 61. Haven't tested it on Safari, IE and Edge yet.

Upvotes: 0

Martin Godzina
Martin Godzina

Reputation: 1575

DISCLAIMER: This is not an answer by any means, but merely a note to the potential other readers trying to use this attribute in a wrong way.


On this non-official W3C reference of the accept attribute, you can find the following:

Tip: Do not use this attribute as a validation tool. File uploads should be validated on the server.

It´s not recommended to use this attribute for validation, because the users could somehow work around it and not all browsers behave the same.

Upvotes: 1

cetver
cetver

Reputation: 11829

Transfer them both mime-type and extension

<input type="file" name="file2" accept="text/csv, .csv"/>

Upvotes: 13

Jacbey
Jacbey

Reputation: 61

First: have you definitely got an html5 doctype?

<!DOCTYPE html>

Cause if you haven't, it might not work in some places.

Second: instead of using html you could use javascript or jquery. See this question / answer: jquery - Check for file extension before uploading

Third: In my experience, some html5 stuff just doesn't work sometimes. I've no clue why but it becomes necessary to get around problems by using jquery, for example.

You should always do a server side validation anyway to make sure that what the user is uploading is in fact what you have limited it to.

Upvotes: 0

Related Questions