0

I am trying to determine the actual MIME type of a file loaded in a web page using <input type="file" accept="image/* onchange="handler()"/>

I want to support the user browsing for any image file, but I need to know the actual MIME type for uploading it to a REST API.

I suppose I could load a file extension mapping table and have a Javascript function to determine the MIME type from the file's file extension. I was just hoping maybe the browser already knows that, and it is somehow available in the DOM.

MarkE
  • 123
  • 8
  • Mime types are an educated guess. The only one that's always correct is `application/octet-stream`. The best guesses typically come from examining the file content, especially the first few bytes ("magic number"). The typical guesses come from examining the filename extension. There are a number of javascript libraries that do the later. – Ouroborus Oct 11 '22 at 17:43
  • Does this answer your question? [How to check file MIME type with JavaScript before upload?](https://stackoverflow.com/questions/18299806/how-to-check-file-mime-type-with-javascript-before-upload) – Ouroborus Oct 11 '22 at 17:45
  • @Ouroborus I figured the browser must need to know the MIME type to render the file which it does successfully for any image file type I choose. It looks like the other information you shared is right on track, I'm going to add it to my code to test if it works as I expect it will. – MarkE Oct 15 '22 at 23:20

1 Answers1

1
function getMimeType(file) {
  const reader = new FileReader();
  reader.onloadend = function() {
    const arr = (new Uint8Array(reader.result)).subarray(0, 4);
    let header = "";
    for(let i = 0; i < arr.length; i++) {
      header += arr[i].toString(16);
    }
    switch (header) {
      case "89504e47":
        return "image/png";
      case "47494638":
        return "image/gif";
      case "25504446":
        return "application/pdf";
      case "ffd8ffe0":
      case "ffd8ffe1":
      case "ffd8ffe2":
        return "image/jpeg";
      default:
        return "unknown";
    }
  };
  reader.readAsArrayBuffer(file);
}

This function takes a file object as an argument and returns the actual MIME type of the file. It uses a FileReader object to read the content of the file and then checks the first few bytes of the file to determine its actual MIME type. Different file formats have different “magic numbers” at the beginning of the file, which can be used to identify the file format.

In the example code, we have included some common file formats and their corresponding magic numbers. You can add more formats and magic numbers to this function as needed.