Javascript API

When using plain upload widget, you might use JS events to handle uploads in the manner you prefer. As you might know both ‘plain’(bare bone) and line(nifty and beautiful) widgets uses hidden field to initialize and to contain file identifier. So, you can bind your own event listeners to that field.

Note about jQuery

UploadCare widgets uses jQuery framework for XHR, animation and other cool stuff. If you use jQuery too, don’t forget to include it before UploadCare script tag to not load jQuery from Google CDN and use your local version instead.

About triggered events

Widgets uses several types of events to which you can bind your own listeners. Available events:

  • uploadcare-progress - trigger when widget start to upload file
  • uploadcare-error - trigger when something awful happens
  • uploadcare-success - trigger when everything is better than expected
  • uploadcare-complete - trigger every time, no matter what happened

JS events intercourse

To bind your own listener, you should simply get hidden input element with jQuery and then use jQuery.bind() method. Let’s use the form from quickstart example:

<form action="/your/upload/handler/" method="POST">
    <p>Your name: <input name="username"></p>
    <p><input type="checkbox" name="robot" value="1"> I'm a robot</p>
    <p>Your photo: <input name="photo" type="hidden" role="uploadcare-plain-uploader"></p>
    <p><input type="submit"></p>
</form>

JS code with jQuery:

UploadCare.ready(function($) {
  var field = $('input[name=photo]');
  var successMsg = $('<span>File uploaded successfully!</span>');
  field.bind('uploadcare-success', function() {
    //In plain widget, actual upload input inserts after hidden field
    successMsg.insertAfter(field.next());
  });
});

JS code without jQuery:

UploadCare._domReady(function() {
  var field = document.getElementsByName('photo');
  var successMsg = document.createElement('span');
  successMsg.innerHTML = 'File uploaded successfully!';

  var success = function() {
    field.parentNode.appendChild(successMsg);
  }

  field.addEventListener('uploadcare-success', success, false);
});

That’s all. Really.

Project Versions

Table Of Contents

Previous topic

Resizing Images

This Page