Plupload - Restrict to only one file

JohnO picture JohnO · Oct 31, 2011 · Viewed 21.1k times · Source

I don't see an option in the plupload API docs on restricting the number of files uploaded, to any number, even 1.

Doc fail? or Feature fail? If it doesn't exist I'll be working on making that happen if anyone needs it..

Answer

Jonathon Bolster picture Jonathon Bolster · Oct 31, 2011

It's a feature fail. I made a wrapper around the jQuery API and this is what I did to make it work for me. My code does some other business logic, but it should give you enough to set started.

Basically, bind to the FilesAdded event and call removeFile on the uploader object (if there are too many files). I think I added the 50ms timeout because it was giving me problems with the file not existing yet.

uploader.bind('FilesAdded', function (up, files) {
    var i = up.files.length,
        maxCountError = false;

    plupload.each(files, function (file) {

        if(uploader.settings.max_file_count && i >= uploader.settings.max_file_count){
            maxCountError = true;
            setTimeout(function(){ up.removeFile(file); }, 50);
        }else{
            // Code to add pending file details, if you want
        }

        i++;
    });

    if(maxCountError){
        // Too many files uploaded, do something
    }

});

max_file_count is something that I add to the pluploader instance when I create it.


Edit: I actually had to do two different ways for this. The above will only allow a person to upload a certain number of files (and generate an error otherwise).

This snippet works in a similar way - but will remove existing files and only upload the most recent:

uploader.bind('FilesAdded', function (up, files) {
    var fileCount = up.files.length,
        i = 0,
        ids = $.map(up.files, function (item) { return item.id; });

    for (i = 0; i < fileCount; i++) {
        uploader.removeFile(uploader.getFile(ids[i]));
    }

    // Do something with file details
});