Cómo limitar el máximo de archivos elegidos cuando se utiliza la entrada de varios archivos


Al usar <input type="file" multiple> es posible que el usuario elija varios archivos.

¿Cómo se establece un límite para cuántos archivos se pueden elegir, por ejemplo, dos?

 40
Author: Félix Gagnon-Grenier, 2012-04-11

5 answers

Puede ejecutar alguna validación del lado del cliente de jQuery para verificar:

$(function(){
    $("input[type='submit']").click(function(){
        var $fileUpload = $("input[type='file']");
        if (parseInt($fileUpload.get(0).files.length)>2){
         alert("You can only upload a maximum of 2 files");
        }
    });    
});​

Http://jsfiddle.net/Curt/u4NuH /

Pero recuerde verificar también en el lado del servidor, ya que la validación del lado del cliente se puede omitir con bastante facilidad.

 41
Author: Curt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-11 12:10:36
<strong>On change of the input track how many files are selected:</strong>

<script>
    $("#image").on("change", function() {
         if($("#image")[0].files.length > 2) {
                   alert("You can select only 2 images");
         } else {
               $("#imageUploadForm").submit();
         }
    });
</script>
<input name="image[]" id="image" type="file"  multiple="multiple" accept="image/jpg, image/jpeg" >
 6
Author: Kristian Antov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-19 20:40:21

También deberías considerar usar bibliotecas para hacer eso: permiten limitar y mucho más:

También están disponibles en https://cdnjs.com/

 2
Author: Ciro Santilli 新疆改造中心 六四事件 法轮功,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-07 05:36:20

Esto debería funcionar y proteger su formulario de ser enviado si el número de archivos es mayor que max_file_number.

$(function() {

  var // Define maximum number of files.
      max_file_number = 3,
      // Define your form id or class or just tag.
      $form = $('form'), 
      // Define your upload field class or id or tag.
      $file_upload = $('#image_upload', $form), 
      // Define your submit class or id or tag.
      $button = $('.submit', $form); 

  // Disable submit button on page ready.
  $button.prop('disabled', 'disabled');

  $file_upload.on('change', function () {
    var number_of_images = $(this)[0].files.length;
    if (number_of_images > max_file_number) {
      alert(`You can upload maximum ${max_file_number} files.`);
      $(this).val('');
      $button.prop('disabled', 'disabled');
    } else {
      $button.prop('disabled', false);
    }
  });
});
 0
Author: David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-04 13:55:30

Use dos elementos <input type=file> en su lugar, sin el atributo multiple.

 -3
Author: Jukka K. Korpela,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-11 12:59:52