5

I am using <input type="file" multiple="multiple"> in my web page to upload files (using ajaxupload). It will allow user to upload multiple files at once. But I want to restrict user to select only 10 files at a time not more than that.

How can I achieve this?

halfer
  • 19,824
  • 17
  • 99
  • 186
nrsharma
  • 2,532
  • 3
  • 20
  • 36
  • 1
    possible duplicate of [Multiple file upload (file input) - limit number of files](http://stackoverflow.com/questions/9813556/multiple-file-upload-file-input-limit-number-of-files) – Mr. Alien Aug 13 '13 at 06:11

2 Answers2

12
<input id="files" type="file" name="files[]" multiple="multiple" onchange="checkFiles(this.files)">

function checkFiles(files) {       
    if(files.length>10) {
        alert("length exceeded; files have been truncated");

        let list = new DataTransfer;
        for(let i=0; i<10; i++)
           list.items.add(files[i]) 

        document.getElementById('files').files = list.files
    }       
}

This function will not allow to select files more than 10.

user8555937
  • 2,161
  • 1
  • 14
  • 39
Ashwani
  • 3,463
  • 1
  • 24
  • 31
  • It gives an error like: "files.slice is not a function". – ozgrozer Mar 10 '19 at 19:21
  • 2
    But is there any way to prevent the user from selecting more than 10 files to begin with? (not handling it after his selection) – Dror Bar Sep 22 '20 at 13:37
  • 1
    @DrorBar There is no way with the current standards to limit it ahead of time. I know that's super frustrating and bad UX, (if you took the time to select 50 images and then it limits you to 10 after you went through all that work it's annoying), but unfortunately there's no mitigation right now. – Nic Estrada Jul 26 '22 at 00:15
0

this piece of code does what you desire and also stops the form from being submitted.

<script>
    $(function() {
        $("button[type = 'submit']").click(function(event) {
            var $fileUpload = $("input[type='file']");
            if (parseInt($fileUpload.get(0).files.length) > 10) {
                alert("You are only allowed to upload a maximum of 10 files");
                event.preventDefault();
            }
        });
    });
</script>
Matt Ke
  • 3,599
  • 12
  • 30
  • 49
Conrad747
  • 45
  • 7