Reputation: 10224
So I want to limit the users options for upload to a list of specific file extensions. This is purely to make it easier for the user, I am already limiting filetype upload on the server also.
I have a list of extensions but not a list of mime types. As the accepted extensions can potentially change, and I don't see any completely reliable way to dynamically calculate their mime types(and would rather avoid this); I would like to instead just feed the extensions into the 'accept' attribute of a <input type="file">
element.
I have noticed this works exactly as intended on Chrome, but not in FF or IE10 (in these browsers it seems to just fallback to all files).
I realise this isn't part of the standard but is there any way to accept extensions instead of mimetypes in the 'accept' attribute that is (modern browser) cross-browser friendly. My test case used <input type="file" accept=".doc,.docx,.bad" />
If this is not possible, what is the best approach? note: I have no garuntee my servers registry will contain all the mimetypes of the extensions I use, and because this list can be very long it is rather impractical (and will be my last resort) to manually keep a list up to date of mimetypes.
Upvotes: 2
Views: 1430
Reputation: 201588
No, it is not safe. The HTML 4.01 accept
attribute is defined so that the value is a comma-separated list of media types. Even this has been implemented relatively recently (e.g., no support in IE 9).
In the HTML5 drafts, the attribute has (recently) been extended to allow extensions as well, and the HTML5 CR description of file input even recommends: “Authors are encouraged to specify both any MIME types and any corresponding extensions when looking for data in a specific format.” However, this has not been widely implemented yet.
It is also conceptually very messy. The media types are by design meant to be a standardized and interoperative way of specifying types of files and other data. Filename extensions are just parts of filenames treated in special ways in some systems, with no standards, beyond some common practices that aren’t very consistent. Mixing the two calls for trouble, though there are some pragmatic reasons behind this.
In any case, in file input, the mapping between filename extensions and media types is performed by the browser together with the underlying operating and file system of the user’s computer; the server is not involved.
Using the File API, you could, on browsers supporting it (e.g., Firefox) check out the filename(s) of the selected file(s) and pick up the filename extension(s) and inform the user if the selected file(s) won’t be accepted. But this would happen after a selection, without affecting the file selection widget, and you could only ask the user to change the choice.
Upvotes: 3