lunes, 1 de septiembre de 2014

Tutorial Javascript parte 27 - Validar input file multiple




En esta parte del tutorial veremos como validar el campo input file a través de la propiedad files que regresa un array con los archivos de subida e iremos validando a través de las propiedades length, type y size.

files -> Almacena en un array los archivos a subir.
length -> Obtiene el total de archivos a subir.
type -> Obtiene el tipo de archivo a subir.
size -> Obtiene el tamaño del archivo a subir.
name -> Obtiene el nombre del archivo a subir.

Código de ejemplo de capítulo ...

<!DOCTYPE HTML>
<html>
<head>

<script>
window.onload = function()
 {
  var btn = document.getElementById("btn");
  btn.onclick = function()
   {
    
 var imagen = document.getElementById("imagen").files;
 
 if(imagen.length == 0)
  {
   alert("La subida de imagenes es requerida");
   return;
  }
 else
 {
  for(x = 0; x < imagen.length; x++)
    {
    
     if (imagen[x].type != "image/png" && imagen[x].type != "image/jpg" && imagen[x].type != "image/jpeg" && imagen[x].type != "image/gif")
  {
  alert("El archivo " + imagen[x].name + " no es una imagen");
  return;
  }
  
  if (imagen[x].size > 1024*1024*1)
  {
  alert("La imagen " + imagen[x].name + " supera el tamaño máximo permitido 1MB");
  return;
  }
  
    }
 }
 
 document.formulario.submit();
   }
 }
</script>

</head>
<body>
<form method="post" name="formulario" enctype="multipart/form-data">
Subir imágenes: <input type="file" multiple name="imagen" id="imagen">
<button type="button" id="btn">Subir</button>
</form>
</body>
</html>


1 comentario:

Anónimo dijo...

Esto no funciona en IE