6

I want to limit user to select up to 6 files in the input tag. Currently, my input tag is like this:

<input type="file" name="question_pic" id="id_question_pic" multiple/>

I would like to limit user to select up to 6 files. I can return an error on the server side but I want client side to change it first.

Is there a way to do that?

Thanks.

Kintarō
  • 2,947
  • 10
  • 48
  • 75
  • Pure html = "max-uploads = 1" or 2 or etc... thought I would throw in file types in case anyone is looking for that too – Sol Dec 30 '18 at 20:02

2 Answers2

7

You can use a jQuery function like this:

$('.fileinput').change(function(){
    if(this.files.length>10)
        alert('Too many files')
});
// Prevent submission if limit is exceeded.
$('form').submit(function(){
    if(this.files.length>10)
        return false;
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • 3
    You can prevent the upload of more then 10 files in the change-function by clearing the filelists value like so: `if(this.files.length>10){ alert('to many files'); this.value = ''; }` Unfortunately you are not allowed to remove items from the filelist object, you only can reset the whole value. – Marc Jul 16 '14 at 08:36
  • Thank you for your input Marc. Does it still stand correct in 2020? – Dror Bar Sep 22 '20 at 13:41
  • @DrorBar Read about the HTML5 File API here to restrict the count of selected files: http://dev.w3.org/2006/webapi/FileAPI/ – Praveen Kumar Purushothaman Sep 22 '20 at 15:03
1

You can use Jquery or Javascript for that like this:

<input type="file" name="question_pic" id="id_question_pic" max-uploads = 6/>

Then in Jquery You can do this like this

Var number_of_uploads;
$("#id_question_pic").change(function() {
    if(number_of_uploads > $(this).attr(max-uploads))
    {
    alert('Your Message');
    }
    else
    {
    number_of_uploads = number_of_uploads + 1;
    }
});

You can also do this on your form submission in which you are uploading the file. But if you are using Ajax upload this is fine I think.

Aleem Ahmad
  • 2,469
  • 4
  • 24
  • 38