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.

1
  • Pure html = "max-uploads = 1" or 2 or etc... <input type="file" name="question_pic" id="id_question_pic" accept=".gif, .jpg, .png, .bmp, .GIF, .JPG, .PNG, .BMP" max-uploads = 1> thought I would throw in file types in case anyone is looking for that too
    – Sol
    Dec 30, 2018 at 20:02

2 Answers 2

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;
});
3
  • 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, 2014 at 8:36
  • Thank you for your input Marc. Does it still stand correct in 2020?
    – Dror Bar
    Sep 22, 2020 at 13:41
  • @DrorBar Read about the HTML5 File API here to restrict the count of selected files: dev.w3.org/2006/webapi/FileAPI Sep 22, 2020 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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.