12

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"?

alex
  • 479,566
  • 201
  • 878
  • 984
khan
  • 343
  • 1
  • 7
  • 17

3 Answers3

12

you can use node-mime

<script src="https://wzrd.in/standalone/mime@latest"></script>
<script>
    mime.getType("something.pdf"); // etc.
<script>
Ahmed elshiekh
  • 141
  • 1
  • 2
8

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.

alex
  • 479,566
  • 201
  • 878
  • 984
  • Just wondering if this answer is still correct seeing as it's 4 years old? Would we still need to maintain the mapping ourselves? – Marklar Jul 19 '15 at 22:47
  • 1
    @Marklar If you don't have a file to upload, but simply an extension, I think you need a mapping. However, seems someone is maintaining one [here](https://github.com/rsdoiel/mimetype-js). – alex Jul 21 '15 at 01:19
  • what if you do have a file to upload? Do you use XHR? – Marklar Jul 21 '15 at 02:19
  • 1
    @Marklar If the user has chosen a file, you can get the mime type out using JavaScript as demonstrated in the answer. – alex Jul 21 '15 at 05:51
-1

https://wzrd.in/standalone/mime@latest is currently not available, so you have to use:

<script>
   import mime  from 'https://cdn.skypack.dev/mime';
   console.log(  mime.getType("file.jpg"));
</script>
Georg Mavridis
  • 2,312
  • 1
  • 15
  • 23