94

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?

rjmcb
  • 3,437
  • 7
  • 30
  • 45
  • 1
    This might be helpful: http://stackoverflow.com/questions/9813556/multiple-file-upload-file-input-limit-number-of-files – Yan Berk Apr 11 '12 at 11:59
  • Possible duplicate of [Count and limit the number of files uploaded (HTML file input)](https://stackoverflow.com/questions/9813556/count-and-limit-the-number-of-files-uploaded-html-file-input) – gbjbaanb Jun 27 '17 at 16:13

8 Answers8

79

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.

Curtis
  • 98,395
  • 62
  • 265
  • 345
  • 15
    I don't really understand why this code is marked as correct answer. It does indeed checks the number of uploaded files however does not disable form submit. jsfiddle code does not have form tag with defined action attribute and it might seem it works fine, however if we extend it by adding form tag it's going to submit the form anyway right after alert appears. – David Jul 04 '18 at 12:45
  • 4
    @David Mostly because people copy and paste stuff all over the place. That and it's been 6 years. – Félix Adriyel Gagnon-Grenier Sep 07 '18 at 04:44
25

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" >
Hien Nguyen
  • 23,011
  • 7
  • 48
  • 55
Kristian Antov
  • 259
  • 3
  • 2
8

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);
    }
  });
});
David
  • 1,851
  • 3
  • 27
  • 34
8

Another possible solution with JS

function onSelect(e) {
    if (e.files.length > 5) {
        alert("Only 5 files accepted.");
        e.preventDefault();
    }
}
Enrique
  • 301
  • 3
  • 8
3

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

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

0

In javascript you can do something like this

<input
  ref="fileInput"
  multiple
  type="file"
  style="display: none"
  @change="trySubmitFile"
>

and the function can be something like this.

trySubmitFile(e) {
  if (this.disabled) return;
  const files = e.target.files || e.dataTransfer.files;
  if (files.length > 5) {
    alert('You are only allowed to upload a maximum of 2 files at a time');
  }
  if (!files.length) return;
  for (let i = 0; i < Math.min(files.length, 2); i++) {
    this.fileCallback(files[i]);
  }
}

I am also searching for a solution where this can be limited at the time of selecting files but until now I could not find anything like that.

Firzok Nadeem
  • 569
  • 5
  • 14
-3

Use two <input type=file> elements instead, without the multiple attribute.

Jukka K. Korpela
  • 187,417
  • 35
  • 254
  • 369
  • 1
    this will only allow one image, he wants 2 images – Diego Oct 15 '16 at 21:36
  • 5
    no, this allows for two separate filelist objects and was consistently used as THE method for both uploading multiple files and limiting their numbers---15 years ago – me_ Sep 27 '17 at 16:09
  • If the requirement is really just "have two different single inputs", then this is actually the best answer @Diego. The question being sadly so unclear, we can't really say. – Félix Adriyel Gagnon-Grenier Sep 07 '18 at 04:47
  • @me_ I'm really curious as to what the solution is now. Hopefully you're not talking about that jQuery cluster over there. That was like, totally rad seven years ago. – Félix Adriyel Gagnon-Grenier Sep 07 '18 at 04:49
  • @Félix Gagnon-Grenier the multiple attribute didn't exist until html 5... regardless of using a library or just plain javascript, the number of files must be checked after files are chosen. I'd say the solution is tell the user no more than a given number of files, and then check file type and number when the popup closes... reject the files object if it exceeds the given number and start again. But no, this is not the best solution--interms of ui alone it is much slower... we have the multiple attribute now, use it. – me_ Sep 18 '18 at 12:12
-7

if you want php you can count the array and just make an if statement like

if((int)count($_FILES['i_dont_know_whats_coming_next'] > 2)
      echo "error message";