Plupload - Restrict to only one file

Based on Jonathon Bolster's second answer, I wrote this simpler snippet to restrict upload to the last selected file:

uploader.bind('FilesAdded', function(up, files) {
    while (up.files.length > 1) {
        up.removeFile(up.files[0]);
    }
});

You can use this max_file_count: 5 where 5 is the max number of upload count.


Other way to do this:

 $(document).ready(function () {
    var uploader = new plupload.Uploader({
        ...
        multi_selection: false,
       ....
     });

Regards


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
});