JS and type.match as file mime type - need advice

user592704 picture user592704 · Sep 13, 2011 · Viewed 46.1k times · Source

Today I faced an interesting thing as FF File API and separate files by their types. OK here is a little snippet as

if (!input.files[0].type.match('image.*')) {
            window.alert("Select image please");
            return;
        }

it controls image being read only. But what about doc files and pdf for example? I couldn't find useful examples for this thing so I hope you can share some snippets. The thing I am interested in detecting different file types but how can I control different file types with JS and its type.match bound?

Here is the base code

Any useful comment is appreciated :)

Answer

Py. picture Py. · Sep 14, 2011

So the base idea is that this code uses File Objects, for more info on them see :

As specified per w3, the type attribute of the File object is a MIME type. This is defined in the RFC 2046. But the spec itself isn't the most interesting part, what's more interesting is the list of the existing MIME type here or the most used one here.

In this code, they use the type attribute and execute a regexp on it (see match and RegExp for more info). Their regexp says that it's ok if the type contains image.

To make your own selector, you'll have to combine the above. (some of the example use === instead of match because the mime type is the entire type) For example the following check are possible:

  • document (not pdf only, odt have this type as well for example) : input.files[0].type==='application/pdf'
  • audio : input.files[0].type.match('audio.*')
  • video : input.files[0].type.match('video.*')

And so on.

After that you can use a selector on the name attribute of the file if you wish to match only certain extension (for example to check between different kind of document, you could look if it's a .pdf, a .odt ...) using for example input.files[0].name.match('\.pdf'). But imho that's not advised, as the user could easily play with that (removing or changing them).