Search code examples
javascriptjqueryfile-uploadplupload

How do I numerically rename files in Plupload before they're uploaded?


I am using the Plupload jQuery UI widget as a basis for my uploader. The widget allows the user to drag reorder the added files.

Upload is begun automatically upon the submission of a form, not manually by the user. During the upload, the UI is blocked so the user can't add anymore files.

Before the upload begins, I need to rename all of the files to upload numerically so that the first file to be uploaded (the one at the top of the jQuery UI widget list) is '1', the second '2' and so on.

For instance, given the following list:

bob.jpg
ann.jpg
doug.jpg
chris.jpg

I want to have them renamed:

1.jpg
2.jpg
3.jpg
4.jpg

This works when the user adds new files or removes existing files. What doesn't work is when the user drag reorders the files. Here is my instantiation code for the uploader:

$('#' + div_id).plupload({
  runtimes: 'html5, flash, silverlight',
  url: 'upload',
  unique_names: false,
  rename: true,
  sortable: true,
  buttons: { browse: true, start: false, stop: false },      

  // Flash settings
  flash_swf_url: 'js/plupload/plupload.flash.swf',

  // Silverlight settings
  silverlight_xap_url : 'js/plupload/plupload.silverlight.xap',

 init: {
   QueueChanged: function(up) {
     for (var i = 0; i < up.files.length; i++) {
       up.files[i].name = (i+1);
     }
   }
 }
});

I can't figure out how to detect when the user drag reorders. Failing that, I don't see an event that fires when the upload of the queue first begins.


Solution

  • In case anyone else comes across this problem:

    Instead of using the QueueChanged() event I simply used jQuery to get every Plupload instance and within jQuery's .each() loop I used this code:

    var regex = /(?:\.([^.]+))?$/;
    for (var i = 0; i < uploader.files.length; i++) {
      var ext = regex.exec(uploader.files[i].name)[1];
      uploader.files[i].name = (ext == undefined) ? (i+1) : (i+1) + '.' + ext;
    }
    uploader.start();
    

    This way I don't do any renaming until immediately before uploading. It also has the added advantage of not renaming the files in the UI widget before upload (this avoiding some confusion to the end user).