How to limit the maximum files chosen when using multiple file input

When using <input type="file" multiple> it's possible for the user to choose multiple files.

How does ones sets a limit for how many files can be chosen, for instance two?


Solution 1:

You could run some jQuery client-side validation to check:

$(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/

But remember to check on the server side too as client-side validation can be bypassed quite easily.

Solution 2:

On change of the input track how many files are selected:

$("#image").on("change", function() {
    if ($("#image")[0].files.length > 2) {
        alert("You can select only 2 images");
    } else {
        $("#imageUploadForm").submit();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>On change of the input track how many files are selected:</strong>
<input name="image[]" id="image" type="file"  multiple="multiple" accept="image/jpg, image/jpeg" >

Solution 3:

This should work and protect your form from being submitted if the number of files is greater then 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);
    }
  });
});

Solution 4:

Another possible solution with JS

function onSelect(e) {
    if (e.files.length > 5) {
        alert("Only 5 files accepted.");
        e.preventDefault();
    }
}

Solution 5:

You should also consider using libraries to do that: they allow limiting and much more:

  • FineUploader. Demo using validation.itemLimit as of 5.16.2:

    var restrictedUploader = new qq.FineUploader({
        validation: {
            itemLimit: 3,
        }
    });
    

  • bluimp's jQuery File Upload Plugin. Usage: jquery file upload restricting number of files using maxNumberOfFiles as of v9.22.0:

    $('#fileuploadbasic').fileupload({
      maxNumberOfFiles: 6
    });
    

They are also available at https://cdnjs.com/