Refile upload with jquery-ui and progress

Ran into a few gotschas while implementing this, so I wanted to share 🙂

– buttons need to be disabled via the button method
– e.originalEvent.detail holds progress information


$(document).on("upload:start", "form", function(e) {
  $(e.target).prev().prev('img').hide(); // hide old image we are replacing
  $(this).find("input[type=submit]").
    button({disabled: true}). // do not let user press submit until image is uploaded
    after('<img src="/images/loading.gif" />') // indicate we are waiting
});

$(document).on("upload:progress", "form", function(e) {
  // http://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable
  function humanFileSize(bytes) {
    var thresh = 1024;
    if(bytes < thresh) return bytes + ' B';
    var units = ['kB','MB','GB','TB','PB','EB','ZB','YB'];
    var u = -1;
    do {
      bytes /= thresh;
      ++u;
    } while(bytes >= thresh);
    return bytes.toFixed(1)+' '+units[u];
  };

  var detail = e.originalEvent.detail;
  var percentage = Math.round((detail.loaded / detail.total) * 100);
  $(e.target).next().text(percentage + "% of " + humanFileSize(detail.total))
});

$(document).on("upload:complete", "form", function(e) {
  if(!$(this).find("input.uploading").length) {
    $(this).find("input[type=submit]").
      button({disabled: false}). // all images uploaded, user can submit the form
      next().remove(); // remove loading
  }
});

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s