Integrate with the jQuery validation plugin

Often times, you have a form with client-side validation rules and some upload fields. You only want to trigger the uploads once the user has filled out the form in a way that follows all validation rules.

This can be tricky, since there are numerous submit handlers involved. This demo, and especially the JavaScript code for it, shows you how to do it. The source code is annotated and all the details are contained in the comments. You can use it right away and enhance it with your own progress bar using the onProgress callback.

<html>
<head><title>Some demo title</title></head>
<body>
<form action="/uploads" enctype="multipart/form-data" method="POST">
  <input type="file" name="my_file" multiple="multiple" />
</form>
<script type="text/javascript">
// Step 1: Load/include jQuery, our jQuery Transloadit plugin, and jQuery validate
// ...

// Step 2: Use the following additional Transloadit Uploader plugin that handles the integration with jQuery validate
// Put it into a different file and include it on your page
(function($) {
  function TransloaditUploader() {}

  TransloaditUploader.prototype.init = function($form) {
    this.$form          = $form;
    this.$files         = this.$form.find('input[type=file]');
    this.uploadBound    = false;
    this.errorTimeout   = 15000;
    this.gotStartEvent  = false;
    this.uploadFinished = false;

    this.bindValidate();
  };

  TransloaditUploader.prototype.bindValidate = function() {
    var self = this;

    // add our validation rules
    this.$form.validate({
      rules: {
        'name': {
          required: true,
          minlength: 2
        },
        'test_file': {
          required: true,
          minlength: 2
        },
      },
      submitHandler: function(form) {
        // this is the most important part
        // if the upload wasn't finished yet, we just trigger the upload,
        // otherwise we submit the form directly and have previously unbound
        // the Transloadit submit handler
        if (!self.uploadFinished) {
          self.triggerUpload();
        } else {
          form.submit();
        }
      },
    });

    // if the user chooses a file, remove the error message
    // for that file input field
    self.$files.change(function() {
      if ($(this).val() != '') {
        var $parent = $(this).parent();
        $parent.removeClass('error');
        $parent.find('label.error').remove();
      }
    });
  };

  TransloaditUploader.prototype.triggerUpload = function() {
    var self = this;

    // now bind our Transloadit jQuery SDK
    this.bindUpload();

    // only trigger the Transloadit upload, no other submit event
    this.$form.trigger('submit.transloadit');

    // if the upload wasn't started within a certain time
    // then we have a connection problem and should show that
    setTimeout(function() {
      if (!self.gotStartEvent) {
        self.uploadError();
      }
    }, self.errorTimeout);
  };

  TransloaditUploader.prototype.bindUpload = function() {
    this.uploadBound = true;
    var assemblyId   = null;
    var self         = this;

    this.$form.transloadit({
      wait: false,
      onStart: function(obj) {
        self.gotStartEvent = true;
        assemblyId = obj.assembly_id;
      },
      onError: function(obj) {
        self.uploadError();
      },
      onSuccess: function(step, result, assembly) {
        // when we are done uploading unbind Transloadit's submit handler
        self.uploadFinished = true;
        self.$form.unbind('submit.transloadit');
        self.$form.find('input[type=file]').parents('.control-group').remove();
      },
      onCancel: function(step, result, assembly) {
        // when we are done uploading, stop all Transloadit actions
        // and, important, unbind its submit handler!
        self.uploadFinished = false;
        self.$form.transloadit('stop');
        self.$form.unbind('submit.transloadit');
      }
    });
  };

  TransloaditUploader.prototype.uploadError = function() {
    // if we have an upload error stop all Transloadit processing
    // and trigger an alert
    this.$form.transloadit('stop');
    alert('Upload error');
  };

  $.fn.transloaditUpload = function() {
    this.each(function() {
      var upload = new TransloaditUploader();
      upload.init($(this));
    });

    return this;
  };
})(jQuery);

// Step 3: Initialize your form with the uploader plugin when the dom is ready
$(function() {
  $('form').transloaditUpload();
});
</script>
</body>
</html>


If you want Transloadit to handle uploads for you, here is some example HTML and JavaScript that can be integrated directly into your website.

We have a great new JavaScript uploader in the works called Uppy and you are welcome to give that a shot, but for now, the following example uses our jQuery SDK and it is still the recommended way to integrate Transloadit into web browsers.

<html>
<head><title>Some demo title</title></head>
<body>
<form action="/uploads" enctype="multipart/form-data" method="POST">
  <input type="file" name="my_file" multiple="multiple" />
</form>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//assets.transloadit.com/js/jquery.transloadit2-v2-latest.js"></script>
<script type="text/javascript">
$(function() {
  $('form').transloadit({
    wait: true,
    triggerUploadOnFileSelection: true,
    params: {
      auth: {
        // Secure via: https://transloadit.com/docs/api-docs/#authentication
        key: "YOUR_TRANSLOADIT_AUTH_KEY",
      },
      steps: {
        "resize": {
          "robot": "/image/resize",
          "use": ":original",
          "result": true,
          "width": 130,
          "height": 130
        }
      }
    }
  });
});
</script>
</body>
</html>

So many ways to integrate

Transloadit's versatility not only shines through in our diverse encoding features, but also in the ways that you can integrate with those. Would you like to handle your own file uploads? Or do you have a big library of files ready to be encoded? You leverage Transloadit's highly scalable encoding platform by letting us import from your source or post files directly from your server using a backend language. We have kits available for most platforms.

If there's no kit available for your platform, you can integrate with our REST API.

Perhaps you want Transloadit to also handle uploads? In this case take a look at our HTML integrations.

Notifying your server

Transloadit will then accept the upload on behalf of your site, process all the files according to your instructions and export to your storage platform of choice. Your visitor will now be able to upload links to the results (example) to your website's /uploads URL.

This takes the pressure off your platform, and ensures the user will have a smooth experience.

Typically, it is advisable to save a record of the result in your database, so you will need to inspect the transloadit POST payload that was sent to your /uploads, or Notification URL. In PHP, that would look like this:

print_r(json_decode($_POST['transloadit'], true));

Here is an example of our PHP SDK.

// Install "transloadit/php-sdk" via Composer (https://getcomposer.org)
use transloadit\Transloadit;
$transloadit = new Transloadit(array(
  "key"    => "YOUR_TRANSLOADIT_AUTH_KEY",
  "secret" => "YOUR_TRANSLOADIT_AUTH_SECRET",
));

$response = $transloadit->createAssembly(array(
  "files" => array(
    "./lolcat.jpg",
  ),
  "params" => array(
    "steps" => json_decode({
      "resize": {
        "robot": "/image/resize",
        "use": ":original",
        "result": true,
        "width": 130,
        "height": 130
      }
    }, true),
  ),
));

This demo uses :original, which indicates a user upload that was received by Transloadit. So, for this SDK, you will likely want to add one of our import Robots and use their downloads instead.

Here is an example of our Ruby SDK.

# gem install transloadit
transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_AUTH_KEY',
  :secret => 'YOUR_TRANSLOADIT_AUTH_SECRET'
)

resize = transloadit.step 'resize', '/image/resize',
  :use => ":original",
  :result => true,
  :width => 130,
  :height => 130
)

assembly = transloadit.assembly(
  :steps => [ resize ]
)

response = assembly.submit! open('./lolcat.jpg')
until response.finished?
  sleep 1; response.reload!
end

if !response.error?
 # handle success
end

This demo uses :original, which indicates a user upload that was received by Transloadit. So, for this SDK, you will likely want to add one of our import Robots and use their downloads instead.

Here is an example of our Node.js SDK.

// npm install --save --save-exact transloadit
import TransloaditClient from 'transloadit'

const transloadit = new TransloaditClient({
  authKey    : "YOUR_TRANSLOADIT_AUTH_KEY",
  authSecret : "YOUR_TRANSLOADIT_AUTH_SECRET"
})

transloadit.addFile("myimage", "./lolcat.jpg");

const options = {
  params: {
    steps: {
      "resize": {
        "robot": "/image/resize",
        "use": ":original",
        "result": true,
        "width": 130,
        "height": 130
      }
    }
  }
}

transloadit.createAssembly(options, (err, result) => {
  if (err) {
    throw new Error(err)
  }

  console.log(result)
})

This demo uses :original, which indicates a user upload that was received by Transloadit. So, for this SDK, you will likely want to add one of our import Robots and use their downloads instead.

Here is an example of our Go SDK.

// go get github.com/transloadit/go-sdk
options := transloadit.DefaultConfig
options.AuthKey = "YOUR_TRANSLOADIT_AUTH_KEY"
options.AuthSecret = "YOUR_TRANSLOADIT_AUTH_SECRET"
client, err := transloadit.NewClient(options)
if err != nil {
    panic(err)
}

assembly := client.CreateAssembly()
assembly.AddFile("myimage", "./lolcat.jpg")

assembly.AddStep("resize", map[string]interface{}{
  "robot": "/image/resize",
  "use": ":original",
  "result": true,
  "width": 130,
  "height": 130
})

info, err := assembly.Upload()
if err != nil {
    panic(err)
}

This demo uses :original, which indicates a user upload that was received by Transloadit. So, for this SDK, you will likely want to add one of our import Robots and use their downloads instead.

Instead of sending encoding instructions directly to Transloadit, you can also save them in a secured way as a "Template". You can then refer to the template_id in your requests, making sure that secrets and instructions no longer have to be transmitted, which might be a security risk in many cases.

Here is the 'raw' Template, in case you would like to save these instructions safely in your account.

{
  "steps": {
    "resize": {
      "robot": "/image/resize",
      "use": ":original",
      "result": true,
      "width": 130,
      "height": 130
    }
  }
}

Try it out

Maximum size for all demos is 100MB.

0% Complete

Transloadit is a service for companies with developers. Visitors are welcome to do one-off media conversions but unfortunately we cannot provide support for that, sorry!