Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File name extension to MIME type

Using only JavaScript and framework like dojo/jQuery...

Is there a way to find the Content-Type for a particular file name extension?

Say if I type in the string "something.pdf", I want to show an alert that says "application/pdf"

or "something.html" show "text/html"?

like image 739
khan Avatar asked Jun 06 '11 00:06

khan


People also ask

What is the extension of MIME file?

MIME (Multipurpose Internet Mail Extensions) is an extension of the original Simple Mail Transport Protocol (SMTP) email protocol. It lets users exchange different kinds of data files, including audio, video, images and application programs, over email.

Is MIME type same as extension?

Whereas file extensions are commonly used for your OS to decide what program to open a file with, Mime types are used by your browser to decide how to present some data (or the server on how to interpret received data). Both are optional but it's a good practice to have an agreement.


1 Answers

I think you will need to maintain the mappings yourself (you could XHR a physical file and get it, but I doubt you want to do that)...

(function() {

    var extToMimes = {
       'img': 'image/jpeg',
       'png': 'image/png',
       ...
    }

    window.getMimeByExt = function(ext) {
        if (extToMimes.hasOwnProperty(ext)) {
           return extToMimes[ext];
        }
        return false;
    }

})();

jsFiddle.

This will return false if it doesn't exist in your mapping. If you like, you could just return the extToMimes[ext], which will give undefined if it doesn't exist. It also won't accidentally get things up the prototype chain.

There is also the option of accessing it if it is a file input.

var mime = $('input[type="file"]').prop('files')[0].file;

Keep in mind the extension to mime type makes no guarantees about the actual file itself; you'd need to parse it server side to determine what kind of file it really is.

like image 131
alex Avatar answered Oct 01 '22 00:10

alex