1

I have a file.svg image and I renamed the file to file.jpg

Now opening this jpg file in the browser definitely would not preview my image. So what i am trying is to detect if the jpg image uploaded via input form is actually jpg within the browser.

I tried reading the file as base64 but couldn't find anything. There is a way to detect if the jpg image is truncated or not here is a reference to that article js check if an image truncated/corrupted data

How can I detect if the image is of correct type as is the extension ?

Ajitesh Singh
  • 401
  • 2
  • 5
  • 14
  • Looks like similar to the following link https://stackoverflow.com/questions/18299806/how-to-check-file-mime-type-with-javascript-before-upload – Kishin Karra May 08 '20 at 13:42
  • 1
    Duplicate of https://stackoverflow.com/questions/18299806/how-to-check-file-mime-type-with-javascript-before-upload – Kishin Karra May 08 '20 at 13:50

3 Answers3

1

Finding the mime type by just looking filename is not safe. You should find exact mime type of a file by reading the signature bytes that is placed in the beginning of the file content.

With this list you can find signature-mime type pairings.

I have written a sample code below where you can check if a selected file is a valid jpeg file or not. JPEG has a simple signature, if the first 2 bytes of the file is 0xFF and 0xD8 you can say that this file is a jpeg file. (please check the list for more complete signature information).

document.querySelector('input').addEventListener('change', function() 
{
 var reader = new FileReader();
 reader.onload = function()
 {
  var bytes = new Uint8Array(this.result);
  if ((bytes[0] == 0xFF) && (bytes[1] == 0xD8))
   console.log("this is a valid jpeg file");
  else
   console.log("this does not look like a jpeg file");
 }
 reader.readAsArrayBuffer(this.files[0]);
});
<input type="file">
Alper Cinar
  • 861
  • 5
  • 12
0

Add an event handler onChange on the input like so:

<input type="file" id="file_uploader" />

Then in javascript add an event handler which will listen for the change on that input:

const file_input = document.getElementById(("file_uploader")

file_input.addEventListener("change", handleChange)

This will automatically pass in the event to handleChange so you can actually reference that:

const handleChange = e => {
    const name = e.targe.file[0].name
    // name = filename.extnesion
    const extension = name.split(".")[1]
}

Split method will give an array of 2 strings - the string before the . - filename, and the string after the . - the extension.

Dimitar
  • 1,148
  • 8
  • 29
  • I am trying to detect if the image is corrupt or not. – Ajitesh Singh May 08 '20 at 13:04
  • So checking for the extesnion wont give you confirmation that the image is actually jpg? – Dimitar May 08 '20 at 13:07
  • I think i did something simmilar a few years ago - obtaining the extension from binary data. Im sure you can get binary data of image in javascript but not so sure about extracting the extension from it. Let me google around for a bit – Dimitar May 08 '20 at 13:11
  • yes we can get the base64 string and even I am trying to figure out a way how to detect the format from base64. I am sure it's possible because there is a website canva.com which detects and prompts with an error – Ajitesh Singh May 08 '20 at 13:17
0

As mentioned by Alper Cinar that reading the extension is not safe and how we can read the starting bytes to identify the mime types. I would like to add a small code snippet for identifying not only mime type of jpg but also for gifs and pngs

      const blob = files[0];
      const fileReader = new FileReader();
      fileReader.readAsArrayBuffer(blob);
      fileReader.onloadend = (e) => {
        const arr = (new Uint8Array(<any>e.target.result)).subarray(0, 4);
        let header = '';
        for (let i = 0; i < arr.length; i++) {
          header += arr[i].toString(16);
        }
        console.log(header);
        let type: any;
        switch (header) {
          case '89504e47':
            type = 'image/png';
            break;
          case '47494638':
            type = 'image/gif';
            break;
          case 'ffd8ffe0':
          case 'ffd8ffe1':
          case 'ffd8ffe2':
          case 'ffd8ffe3':
          case 'ffd8ffe8':
            type = 'image/jpeg';
            break;
          default:
            type = 'unknown';
            break;
        }
        console.log(type);

      };

For detailed reference How to check file MIME type with javascript before upload?

Ajitesh Singh
  • 401
  • 2
  • 5
  • 14