Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plupload - Restrict to only one file

Tags:

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..

like image 577
JohnO Avatar asked Oct 31 '11 17:10

JohnO


2 Answers

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
});
like image 113
Jonathon Bolster Avatar answered Dec 19 '22 01:12

Jonathon Bolster


Other way to do this:

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

Regards

like image 29
octavioccl Avatar answered Dec 19 '22 00:12

octavioccl