Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...