Ajitesh Singh
Ajitesh Singh

Reputation: 461

Detect within the browser if the image uploaded is of correct format

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 ?

Upvotes: 1

Views: 1277

Answers (3)

Ajitesh Singh
Ajitesh Singh

Reputation: 461

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?

Upvotes: 0

Alper Cinar
Alper Cinar

Reputation: 861

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

Upvotes: 1

Dimitar
Dimitar

Reputation: 1180

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.

Upvotes: 0

Related Questions