npm.io
1.1.1 • Published 7 years ago

mimesniff

Licence
MIT
Version
1.1.1
Deps
0
Size
7 kB
Vulns
0
Weekly
0

MIME Sniffing for the Browser

Do you not trust your the mime type determined by your browser, you shouldn't. Most browsers will take a file's extension to determine MIME type. Using getMIMEType(file) will try sniff the file type:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>MIME test</title>
    <script src="index.js"></script>
  </head>
  <body>
    <input id="file" type="file" />
    <ol></ol>
    <script type="text/javascript">
      document.getElementById('file').addEventListener('change', (e) => {
        for (let file of e.srcElement.files) {
          const li = document.createElement('li');
          getMIMEType(file)
            .then(
              text => li.innerText = text,
              text => li.innerText = `${error} -> I'll use the browser supplied one: ${file.type}`
            ) 
            .then(() => document.querySelector('ol').appendChild(li));
        }
      });
    </script>
  </body>
</html>

Can sniff:

Category Type
audio aiff
audio mpeg
application ogg
audio midi
video avi
audio wave
image bmp
image gif
image gif
image webp
image png
image jpeg
application x-gzip
application zip
application x-rar-compressed
application postscript
application pdf

Develop

Want to add support for more types? Take a look at the MIME Sniffing living standard.

Keywords