How can restrict user to upload max 10 files at once?

nrsharma picture nrsharma · Aug 13, 2013 · Viewed 7.8k times · Source

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?

Answer

Ashwani picture Ashwani · Aug 13, 2013
<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.