How to check if the file is an Input type="file" image

Asked

Viewed 1,299 times

0

I have an input type="file" that would suit the user to add a profile photo and would like to check if the file is an image before.

I have already checked via PHP, but I would like to do via Javascript also.

3 answers

0


Yes, including, you can add in HTML too if you don’t know:

<input type="file" accept="image/*"/>

I’ll give you the basis, then just implement conditions:

function validation(){
  var file = document.getElementById("myFile");
  var file = file.files[0];
  
  document.getElementById("logger").innerHTML = "Nome: " + file.name + " <br />Type: " + file.type + "<br />Tamanho: " + file.size;
}
 <input type="file" id="myFile" accept="image/*" onchange="validation()" />

  <br />
  
  <div id="logger">
    
  </div>

  • Thanks man, I really didn’t know, thanks.

0

You can use the attribute type of the file, it will return the type in the format image/png, just check if it contains the text image

Ex.:

var file = document.getElementById('file');

function test() {
    if (file.files[0].type.includes('image')) {
        alert('É uma imagem')
    } else {
         alert('Outro tipo de arquivo')
    }
}

document.getElementById('testButton').addEventListener('click', test)
<input type="file" id="file">
<button id="testButton">Testar</button>

Note: The type is detected from the file extension, which cannot be very safe


I made another example based on this reply, is more complex, but more secure than the previous:

var fileInput = document.getElementById('fileInput')
var fileReader = new FileReader();

fileReader.onloadend = function(e) {
    var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
    var header = "";
    for(var i = 0; i < arr.length; i++) {
       header += arr[i].toString(16);
   }
    var type = ""

    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"; // Or you can use the blob.type as fallback
            break;
    }
    
    alert(type)
};

fileInput.addEventListener('change', function () {
    var blob = fileInput.files[0]
    fileReader.readAsArrayBuffer(blob);
})
<input type="file" id="fileInput"/>

0

You can check by using file extension .match with the regex:

/\.(gif|jpg|jpeg|tiff|png)$/i

Example:

function isImagem(i){
   
   var img = i.value.split(".");
   var ext = "."+img.pop();

   if(!ext.match(/\.(gif|jpg|jpeg|tiff|png)$/i)){
      alert("Não é imagem");
      i.value = '';
      return;
   }

   alert("OK!");
}
<input type="file" onchange="isImagem(this)" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.