Get File MIME Type in JavaScript

Getting the MIME type is a more robust way of finding what kind of data a file actually contains compared to checking the file extension.

 

For example, a file might have a .jpg extension but the data might not be image/jpg at all – it could be anything in theory.

 

In JavaScript, we can access the mime type of a user uploaded file with the .type property. Here is an example of checking a file input has changed, looping through the files object and getting the MIME type for each file.

 

<input type="file" name="upload" id="upload">
var elm = document.getElementById('upload');

elm.addEventListener('change', function() {
  if (window.FileReader && window.Blob) {
    var files = elm.files;

    for (let i of files) {
      console.log(i.type);
    }
  } else {
    alert('Please update your browser to support this feature.');
  }
});
image/png

 

Checking MIME types won't improve the security of your app since they can easily be spoofed, but it should make it more robust when dealing with mislabeled files. As a rule of thumb, all critical validation should be double-checked server-side as front-end JavaScript can be manipulated.