I have an input type="file" that would serve the user to add a profile photo and would like to check if the file is an image before.
I've done the verification via PHP, but I'd like to do it via Javascript too.
I have an input type="file" that would serve the user to add a profile photo and would like to check if the file is an image before.
I've done the verification via PHP, but I'd like to do it via Javascript too.
Yes, inclusive, you can also add to HTML if you do not know:
<input type="file" accept="image/*"/>
I'll give you the base, 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>
You can use the type
attribute of the file, it will return the type in image/png
format, 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: Type is detected from file extension, which can not be very secure
I made another example based on this answer , it is more complex, but more secure than the previous one:
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"/>
You can check for file extension using .match
with 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)" />