Comment puis-je limiter le type MIME à png et jpg uniquement avec file.type.match
ci-dessous est mon code
var fileInput = document.getElementById("myfileinput").files[0]; if (fileInput.type.match('image/jpeg')) //I not thinking to use if(xx || xx) //prefer using var mimeType = jpg,png many sortinges but not work { alert("Right"); }else{ alert("wrong"); }
D’après votre question, il semble que vous ne vouliez pas faire quelque chose comme:
if (fileInput.type.match('image/jpeg') || fileInput.type.match('image/png')) //I not thinking to use if(xx || xx) //prefer using var mimeType = jpg,png many sortinges but not work { alert("Right"); }else{ alert("wrong"); }
Vous pouvez créer un tableau d’extensions acceptables et les parcourir de la manière suivante:
var fileInput = document.getElementById("myfileinput").files[0]; var allowed = ["jpeg", "png"]; var found = false; allowed.forEach(function(extension) { if (fileInput.type.match('image/'+extension)) { found = true; } }) if(found) { alert("Right"); } else{ alert("wrong"); }
Voir ce violon pour un test.