Validate multiple files with jquery

1

How are they? You will see I am doing a validation with jquery of uploading multiple files for which I have this in the html code:

<input type="file" name="name_imagen[]" multiple="multiple" id="name_imagen">

and this with jquery:

$(function(){
    $("input[type='submit']").prop("disabled",true);

    $("input[type='file']").bind('change',function(){
        var a = 0;
        var imageSize = $("#name_imagen").files.size;
        var ext = $('#name_imagen').val().split('.').pop().toLowerCase();
        for(var i = 0; i < imageSize; i ++){
            var imageSize1 = imageSize.files[i].size;
            if(imageSize1 > 1000000){
                alert("Mayor a lo permitido");
            }
        }
    });
});

When I try it, I get this error:

  

Uncaught TypeError: Can not read property 'size' of undefined

I do not know what I'm doing wrong. To this I want to add the validation by file extension.

Help please. Thanks

    
asked by Jonathan Cunza 06.09.2016 в 22:19
source

1 answer

1

The problem is inside the loop you have:

var imageSize1 = imageSize.files[i].size;

should be:

var imageSize1 = imageSize.size;

On the other hand I show you other ways to go through a Array-Like Object , simply "uncomment" the commented lines and watch the output:

$("input[type='file']").bind('change',function(){
  // Esto es un Array-like Object
  //console.log(name_imagen.files);
   
  //var prueba = Array.from(filesObj);
  //console.log(prueba);
  
  var filesObj = name_imagen.files;

  var filesArray = Object.keys(filesObj).map(function(key){
    return filesObj[key];
  });
  
  filesArray.forEach(function(file){
    if (file.size > 1000000) 
      console.log('El archivo ${file.name} tiene un tamaño (${file.size}) mayor del permitido');
    else 
      console.log('El archivo ${file.name} tiene un tamaño (${file.size}) CORRECTO!!!!!')
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="name_imagen" multiple="multiple" id="name_imagen">
    
answered by 06.09.2016 / 22:46
source