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

2

6

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?

Frequency answered 13/8, 2013 at 6:7 Comment(1)
possible duplicate of Multiple file upload (file input) - limit number of filesSchizogenesis
B
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.

Bander answered 13/8, 2013 at 6:35 Comment(3)
It gives an error like: "files.slice is not a function".Macaroon
But is there any way to prevent the user from selecting more than 10 files to begin with? (not handling it after his selection)Spinach
@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.Virtuosity
T
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>
Tracheid answered 10/7, 2020 at 13:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.