Restrict file types in an input

0

Is it possible in a file-type input to restrict the formats it can accept when selecting files?

    
asked by Marco Eufragio 25.10.2018 в 00:07
source

2 answers

1

With jquery you can do this:

$("#archivo").on("change", (e) => {
  const archivo = $(e.target)[0].files[0];
  let nombArchivo = archivo.name;
  var extension = nombArchivo.split(".").slice(-1);
      extension = extension[0];
  let extensiones = ["jpg", "png", "jpeg"];
 
  if(extensiones.indexOf(extension) === -1){
    alert("Extensión NO permitida");
  }else{
    alert("Extensión permitida");
  }
  
});
<form>
  <input type="file" name="archivo" id="archivo" />
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The idea is to get the name of the file and there also get the extension and then compare it with an array where you have all the extensions allowed.

I hope it serves you.

    
answered by 25.10.2018 / 03:27
source
1

with the accept attribute you can filter on the client's side, but you must also validate on the server.

<form>
  <input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
</form>
    
answered by 25.10.2018 в 01:22