1. Basics

1.1 How to Read the Docs

Welcome to our documentation section! There are 3 main pages in our docs. These are:

  1. The Integration page, the one you are on right now. It explains the basics of our API service, such as terminology, the flow of things and how to build encoding instructions. It shows you all the possibilities concerning integration with the service.
  2. The API page explains the different available endpoints, their request and response signatures, as well as how to authenticate yourself with the API.
  3. The Robots page gives an overview of all the available conversion types (image resizing, video encoding, etc.) and their available parameters.

The remaining three tabs in our header are Best Practices, Formats, and FAQ. These pages can be used for further reference.

We recommend that you first read through this Basics section. After that, you will want to check out all the different conversion features that are listed in Robots.

:bulb: Note that we have a :sparkles: Wizard that can help you discover your ideal & copy-pastable integration code in under a minute.

1.2 Introduction

What We Offer

We offer all of the required components to manage file uploads and conversions for your web or mobile applications:

  1. Browser (Uppy, jQuery) and Mobile (Android, iOS) plugins so that Transloadit can directly handle your user's uploads, process them, and save the results to the storage platform of your choosing.

  2. A REST API to let us encode/resize/convert/etc the images/video/audio/documents/etc that are already in your possession.

  3. Development Kits for all major languages, that make it easier to leverage this REST API.

  4. A command-line interface utility called Transloadify to have us encode files straight from the command line without writing a single line of code.

The Basic Flow

  1. You send files via a POST request to our API, either manually with Curl or with one of our SDKs.
  2. Transloadit processes the files, encodes videos, resizes images, etc.
  3. We notify your app with a POST request at a callback URL and include JSON containing the meta and URLs of the encoding results.
  4. In your back-end, you store the URLs to the result files in your database and display beautiful videos and images to your users.

The Basic Flow With jQuery

Our jQuery SDK is really helpful when you want to use Transloadit with HTML forms.

  1. If you include the SDK on your HTML page, you can add Transloadit capabilities to any form. When your user submits the form, the selected files are uploaded to Transloadit.
  2. Transloadit processes the uploaded files, for example by encoding videos, resizing images, and storing the results on Amazon S3.
  3. Once processing is completed, the jQuery SDK attaches the result JSON in a hidden field called transloadit to your form. Then, the form is submitted as usual.
  4. In your back-end, you analyze the result JSON from the transloadit form field and store the URLs to the result files in your database. Then you display beautiful videos and images to your users.

Terminology

  • Assembly

    An Assembly is the execution of file conversion instructions (called Assembly Instructions) on uploaded and/or imported files. Each Assembly has a unique assembly_id identifier that can be used to refer to the Assembly in subsequent API requests.

  • Assembly Instructions

    The set of Assembly Steps that is executed on the uploaded/imported files by the Transloadit backend.

  • Assembly Step

    A single file conversion Step that files undergo during an Assembly. Each Step performs some type of encoding, resizing or conversion. You are free to name Steps however you like in the Assembly Instructions.

  • Robot

    Transloadit offers many features for processing files, that we have condensed in Robots. One Robot can do one thing really well, such as: image resizing. When you integrate with Transloadit, you can combine many Robots and put them to work in an Assembly, one Robot handing its results to the next. This allows to create unimagined workflows and encoding pipelines, unique to your use case.

  • Template

    A Template allows you to save Assembly Instructions securely in your account on transloadit.com. That way, you can hide these instructions from your users. You would then reference them via a template_id parameter in your API request, making your requests lightweight and secure.

  • Assembly Status

    When an Assembly has been created, an Assembly Status URL is returned. At this URL endpoint, you can find all kinds of useful information about the Assembly in JSON format. This includes the Assembly's id, its uploads, its results (appended as they are processed), its execution duration, and much more. You can fetch the URLs to your result files from the Assembly Status and then display them, or save them in your database.

  • Assembly Notification

    You can be notified when an Assembly has finished executing by having the Assembly Status sent in a POST request to a URL of your choice. Using Assembly Notifications is entirely optional.

  • Assembly Replay

    Assemblies are executed on a large pool of servers and sometimes it happens that a server malfunctions. If your Assembly Instructions were saved in a Template, and as long as the uploads (if any) completed succesfully, Transloadit is able to replay Assemblies within 24 hours. We will attempt to do so automatically in cases where the Assembly Status is ASSEMBLY_CRASHED (which means that a server malfunctioned), but it can also be triggered manually in the account section of our website.

  • Assembly Variable

    Assembly Variables are special placeholders such as ${file.original_basename} that can be used in any Robot to dynamically influence its encoding behavior based on the currently converted file or the values of hidden fields in the submitted HTML form.

  • Encoding Job

    The smallest processing unit in the Transloadit vocabulary, such as a single video encoding, or an image resize, to be executed on our encoding machines.

  • Job Slots

    An Encoding Job can take up to 8 Job Slots depending on the estimated required machine capacity. Jobs Slots occupied by a single customer or IP are summed up to determine when Encoding Jobs trickle down from the Live Queue into Batch Queue.

  • Job Slot Limit

    The configurable per-customer-value that determines when Encoding Jobs trickle down from the Live Queue into Batch Queue.

  • Live Queue

    Small Jobs that require a realtime-feel to it are handled in this queue. Transloadit continously optimizes so that there never is a Live Queue.

  • Batch Queue

    Slower processing can happen when Encoding Jobs are downgraded to the Batch Queue. This happens on customer request, for Jobs that are the result of an Import Robot, or when there is a large volume of Jobs by a single IP or Customer.

  • Auth Key

    The Auth Key can be regarded as your Transloadit username for use in automation. Your Auth Key is not secret and can be used to publicly identify your account.

  • Auth Secret

    The Auth Secret can be regarded as your Transloadit password for use in automation. Only you and Transloadit should know your Auth Secret. If you suspect your Auth Secret has been compromised, you are advised to generate a new one, which automatically invalidates the old one.

  • Rate Limiter

    To protect customers from other customers' mistakes, we limit the number of Assemblies that can be created to 250 per minute, up to a default maximum of 250 concurrent Assemblies. If your use-case warrants a higher limit, we can adjust this for you upon request.

  • REST API

    Our REST API provides programmatic access allowing Transloadit to start encoding jobs for you. It is available over plain HTTP(S), which means you can integrate with us using any platform or language that is able to communicate with it. We do, however, recommend using one of our SDKs. These provide boilerplate for common operations and will save you valuable coding time.

  • Signature Authentication

    With Signature Authentication, you use an Auth Secret that is known only by you and Transloadit to encrypt intructions and an expiration date. When the Assembly Instructions arrive at Transloadit, we will also encrypt them along with the expiration date, in order to verify whether the resulting signature matches the one you provided. Enabling Signature Authentication ensures that Assembly Instructions cannot be tampered with by anybody who does not know your Auth Secret. People will also not be able to submit Assemblies on your behalf, driving up your invoices.

  • Signature Authentication for Notification

    With Signature Authentication for Notifications, you use an Auth Secret that is known only by you and Transloadit, which Transloadit then uses to encrypt results, intructions and an expiration date. When the Notification arrives at your backend, you will also encrypt it along with the expiration date, in order to verify whether the resulting signature matches the one we provided. With Signature Authentication for Notifications you can be sure that it was Transloadit who sent you the Notification, and that it hasn't been tampered with by anybody who does not know your Auth Secret.

1.3 The Minimal Integration

The following step-by-step guide explains how to implement a minimal image resize upload using Transloadit. For the sake of simplicity, this for now assumes the jQuery SDK.

Step 1: Create Your Account

Create a new account using our signup page. Your API credentials will be generated automatically. When you have signed up, you can log into your account.

Step 2: Create the Upload Form

In your web page, edit the source of the page and add the HTML for a form:

<form id="upload-form" action="/uploads" enctype="multipart/form-data" method="POST">
  <input type="file" name="my_file" />
  <input type="submit" value="Upload">
</form>

Make sure that enctype is set to multipart/form-data. If this is not done correctly, browsers will not understand that this form is used to upload files.

Additionally, your file input field(s) must contain a name attribute.

Step 3: Add the jQuery SDK

The Transloadit jQuery SDK provides some additional functionality, allowing you to:

  • show file upload progress,
  • get upload results directly without further API queries
  • wait for all file conversions to complete before final form submission.

You can use the following HTML/JavaScript to add our jQuery SDK:

<!-- You can choose jQuery version 1.9.0 or any newer version here -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//assets.transloadit.com/js/jquery.transloadit2-v2-latest.js"></script>
<script type="text/javascript">
$(function() {
  $('#upload-form').transloadit({
    wait: true,
    params: {
      auth: { key: "YOUR_TRANSLOADIT_KEY" },
      steps: {
        resize_to_75: {
          robot: "/image/resize",
          use: ":original",
          width: 75,
          height: 75
        }
      }
    }
  });
});
</script>

Please make sure you replace YOUR_TRANSLOADIT_KEY with the key found on the API credentials page.

The wait parameter specifies whether Transloadit should wait for all files to be processed before submitting the final form. In this case, it means Transloadit will first wait for all uploaded files to be resized to 75x75 pixels before submitting the final form. If you set it to false you will require Transloadit to notify you when the file processing is done. But more on that later.

The steps object allows you to set the Assembly Instructions (the collection of Assembly Steps) you want to use. You can use as many Steps as you want and you can also name them however you like! We only specify one Step here, which uses the /image/resize Robot, and specifies use: ":original", which means the Robot should use the originally uploaded files as input. You can also specify names of other Steps for the use parameter, but we'll learn more about that later.

Hint Using the jQuery SDK or one of our other development kits is the advised way of integration. However, by changing a few things, you can also get it to work without JavaScript enabled. Read more about that here.

Step 4: Testing

Now that the form is done, we are ready to upload a file. By default, this will display an overlay with a progress bar when a file is uploaded.

On your back-end page, return the incoming POST data to display the results that Transloadit appended to the form. For example, use something like the following for PHP:

The result of the print_r should be something like this:

Transloadit provides information about all uploaded files (the uploads key), as well as about all produced result files (the results key). Both can be found as arrays in the result JSON. This is to support all use cases, including having multiple uploaded files and multiple encoding results.

Hint To see a working example of what we just built, see this demo page. The Assembly Instructions differ slightly, but it should nevertheless give you a good idea of how things work.

Specifying Assembly Instructions in the Form

Alternatively, you could also have added the Assembly Instructions in a hidden form field named params. Sometimes, especially when your instructions need to be calculated by a back-end language, it is easier to specify them directly in the form, than to add them in the call to the jQuery SDK

The contents of the hidden params field need to be encoded as JSON, with HTML entities escaped. Have your preferred scripting language encode the JSON for you to maintain readability. Here is an example in PHP:

$params = array(
  "auth" => array("key" => "YOUR_TRANSLOADIT_KEY"),
  "steps" => array(
    "resize_to_75" => array(
      "robot" => "/image/resize",
      "use" => ":original",
      "width" => 75,
      "height" => 75
    )
  )
);

printf(
  '<input type="hidden" name="params" value="%s" />',
  htmlentities(json_encode($params))
);

Your form should then look like this (just with YOUR_TRANSLOADIT_KEY replaced with your real Auth Key):

<form id="upload-form" action="http://api2.transloadit.com/assemblies" enctype="multipart/form-data" method="POST">
  <input type="hidden" name="params" value="{&quot;auth&quot;:{&quot;key&quot;:&quot;YOUR_TRANSLOADIT_KEY&quot;},&quot;steps&quot;:{&quot;resize_to_75&quot;:{&quot;robot&quot;:&quot;\/image\/resize&quot;,&quot;use&quot;:&quot;:original&quot;,&quot;width&quot;:75,&quot;height&quot;:75}}}" />
  <input type="file" name="my_file" />
  <input type="submit" value="Upload">
</form>

Both ways of adding the Assembly Instructions to your form are valid. When you upload a file you should see the same result.

Closing Remarks

That's it already for the minimal integration - it was pretty simple wasn't it? If you want to there is a lot more that you can do, though.

For example, specifying your Assembly Instructions directly in the form or in your JavaScript makes them publicly visible. That is why you will learn about Templates later on, in order to hide Assembly Instructions within your Transloadit account.

In addition to this, you might have noticed that your Auth Key is also publicly visible using this integration method, potentially allowing anyone to upload files on your behalf and driving your Transloadit bill up. To prevent this, we offer Signature Authentication in order to make sure that only you and your users can create Assemblies in your account. After all, we want to make sure things are secure. Please learn about Signature Authentication here.

The jQuery SDK is not the only way you can integrate with Transloadit. We offer Software Development Kits for all major platforms and there are also a lot of community projects that you can use and learn from. And if none of the SDKs and community projects suit your requirements, then you could also write your own code to integrate with our REST API.

1.4 Assembly Instructions

Basics

Processing files lies at the heart of Transloadit. For that reason, we have crafted a simple JSON format that enables Transloadit to do just about anything with your files. Here is a simple example:

{
  auth: { key: "YOUR_TRANSLOADIT_KEY" },
  steps: {
    encode: {
      robot: "/video/encode",
      use: ":original",
      preset: "iphone"
    },
    export: {
      robot: "/s3/store",
      use: "encode",
      bucket: "YOUR_AMAZON_S3_BUCKET"
      key: "YOUR_AMAZON_S3_KEY",
      secret: "YOUR_AMAZON_S3_SECRET",
    }
  }
}

These instructions consist of two Assembly Steps, encode and export, but you can name your Steps any way you want. Giving them names (instead of numbers) makes it easier to reference them.

Each Step is defined as a JSON object with a robot and use key. These keys specify which Robot should be used for the Assembly Step and which other Step the Robot should use as its conversion input. By using :original you state that the originally uploaded files should be used as input.

All other parameters will be used for the file conversion itself.

Special Parameters

Special parameters instruct the Assembly engine itself. They control the order and behavior of your Steps.

Parameter Description

robot

Specifies which processing robot to use for the Step.
Robots only accept certain file types. File types they cannot process will be ignored, without additional warning. The /video/encode Robot, for example, will ignore images and the /image/resize Robot will ignore videos.

use

Specifies which Assembly Step to use as the input for this Step.
This parameter is mandatory
Please use the value ":original" to reference uploaded files.

You can also specify an array, when you want to use several Steps as the input for your step: use: [ ":original", "my_video_encode" ]

By default, the Assembly engine passes every file individually through all Steps. If you would like to change that, then you need to use Step bundling.

Step bundling
Some Robots like /video/adaptive and /file/compress allow you to use a combination of several Steps as the input. In the case of the /file/compress Robot for example, you may not want to create one zip file for each of your uploaded files. Instead you may want to create one zip file that holds all the uploaded files. In this case you would set bundle_steps to true, like in this example:

use: { steps: "segment_step_name", bundle_steps: true }

Please keep in mind that all input Steps must actually be present in your Template when using Step bundling. If one of them is missing, the Assembly will just complete without the Robot having done its job.

Supporting multiple uploaded files with step bundling
When using the mentioned Robots you may also have multiple uploaded files and you want to create a media playlist for each of them. To achieve this, please set group_by_original to true. This will create a separate playlist based on the segments for each of your uploaded or imported files, instead of creating a playlist containing all segments of all uploaded and imported files. Here is an example:

use: { steps: "segment_step_name", bundle_steps: true, group_by_original: true }

Demo
See a demo for the use parameter here.

result

Controls whether the results of this Step should be returned.
If set to true, this Step will occur in the Assembly's result JSON with a temporary URL referencing the result file.
For your convenience, this is automatically set to true for any Steps that have no subsequent Step and false for all "in-between" steps.

If you set this parameter to false, this Step will not occur in the Assembly's result JSON, which can be useful if you want to keep the JSON small.

Executing Assembly Instructions

Transloadit aims to process as much as possible in parallel. Steps will be executed as soon as their input Steps are available. For example, let's say you want to encode an uploaded video and would also like to extract thumbnails from it:

Both the encode and the thumbs step will be executed in parallel as soon as the file upload is finished.

The export step is set up to use the results of encode and thumbs, and will spawn an internal job for each file as soon as the results of these Steps become available.

As you can see, this format makes it easy to execute instructions as fast as possible.

Examples

Please check out our demo section for various examples of both simple and complex Assembly Instructions.

1.5 Templates

Securing Your Assembly Instructions

Specifying Assembly Instructions directly in the params field of a form is very convenient. However, since anyone visiting your site can easily read your HTML source and find out your Assembly settings, this also has two major downsides,:

  • Embedded secrets, such as S3 and SFTP access credentials, can be seen by anyone in your HTML source!
  • Assembly Replays will not work, because we obfuscate embedded secrets when the Assembly is finished.

To counter these issues, we offer Templates.

Templates allow you to store Assembly Instructions securely on our servers, by using 256 bit AES encryption and then including the Template's ID in a template_id key in the hidden params input field (or the call to the jQuery SDK).

This is useful for Assembly Instructions that use storage robots requiring service access credentials (such as the S3 robot).Templates can be used to hide your secret credentials, by keeping them from showing up in your HTML source.

Assembly Replays will also work properly, because they can read the storage credentials straight from your Templates. When you only use the params, the credentials are obfuscated for security reasons and replays will not be able to decrypt them.

Templates are the absolutely recommended way of integrating Transloadit. If you are not using Templates at all, you are either prone to security issues or unable to replay failed Assemblies - or both. You should only consider not using Templates for very simple one-time file conversion jobs. For integrating Transloadit into your apps Templates should always be used!

The jQuery SDK's params object will be merged into the Template that you use, giving you a good means to overwrite your Templates on the fly. Think of an image cropping tool that allows your users to select a cropping area. You will want to overwrite the coordinates in your Template with the coordinates that your user selected. There really is no good reason to not use Templates.

How to Create a Template

  1. Log in to your Transloadit account on the website.
  2. Click on the "Templates" link under "My Account" and then click "Create template".
  3. Give your Template a name for future reference.
  4. Provide the JSON Assembly Instructions for your Template and hit save.

Once the Template is saved, a page is displayed showing the Template you created. At the top of the page, the Template's template_id is shown, such as "4b62ee4dbb38455d96fe13d972ec3211". You can then attach this ID to the template_id parameter in your Transloadit form parameters.

Hint The website also has a testing area where you can test your Templates with an upload form, without updating your own HTML forms.

How to Use a Template

Once you have a template_id, you can use the Template in a form by replacing the Assembly Steps in the jQuery SDK's params object with the Template ID. For example, take the following:

With a Template, this would become something like this:

{
  $(function() {
    $('#upload-form').transloadit({
      wait: true,
      params: {
        auth: { key: "YOUR_TRANSLOADIT_KEY" },
        template_id: "4b62ee4dbb38455d96fe13d972ec3211"
      }
    });
  });
}

1.6 Saving Conversion Results

Once your upload form is submitted (or the Assembly Notification was sent) and you have received the results from Transloadit, you can save the URLs of the result files in your database.

You can find an uploads key and a results key in the response JSON, which contain your original file uploads and the conversion results respectively. You can learn more about the response JSON and how it is formatted here.

Important Transloadit will save your files only temporarily. These temporary file URLs expire after 24 hours, making them inaccessible. To persist your files longer than 24 hours, you can use any of the following storage Robots:

  • /azure/store , which exports encoding results to Microsoft Azure
  • /cloudfiles/store , which exports encoding results to Rackspace Cloudfiles
  • /ftp/store , which exports encoding results to your FTP servers. No public key authentication is required. This Robot relies on password access
  • /s3/store , which exports encoding results to Amazon S3
  • /sftp/store , which exports encoding results to your own SFTP server
  • /softlayer/store , which exports encoding results to Softlayer / IBM Cloud
  • /youtube/store , which exports encoding results to YouTube

Transloadit is good at extracting metadata from uploaded files. So, in addition to saving the URLs of the result files, you may want to consider saving the metadata as well. Users often appreciate seeing more information about the video or image they are looking at.

You are free to integrate any web services or tools for displaying your files on the web as you see fit. For displaying video, check out players such as flowplayer or mediaelementjs.

1.7 Speeding Things Up

In this section we will explain how you can speed things up, giving your end-users a smoother experience.

Uploading Times

We have many machines that are dedicated to receiving uploads. For redundancy purposes, we have clusters in both Europe and the United states. This also results in lower latency, since your users will be serviced by the machines closest to them.

Queue Times

Encoding is hard work for computers, so we use high end machines. We maintain an overcapacity of 300% to handle traffic spikes. This ensures that we rarely have a queue. We can't rule this out completely, however, as customers could still send us tough jobs faster than we can process them.

When our scaling software foresees a queue, new machines are launched to drain the queue. It takes five minutes for a machine to come online and we can launch up to 1500 of these in parallel.

You can see our current queue times for image conversion and video encoding on our Statuspage. You can also programmatically check them by accessing Queue API endpoint, which shows the queue times in number of seconds.

Even though queues are a rare thing, especially since we continually optimize for even faster encoding times, sometimes it just takes a few minutes. This is why we recommend to implement Transloadit in an asynchronous way: as soon as your users finish the upload, they do not need to wait for file processing to complete. We will contact your app programmatically when the processing is done, after which you can notify your user via web / ajax / email and display the files.

If you want to use our jQuery SDK, we advise you to set its wait parameter to false and use Assembly Notifications instead. By doing this, your users will only have to wait for the uploading of the files to finish and then they can move on. Once Transloadit is done processing your files, we will notify you at the notify_url with a POST request and you can start displaying files to your users.

This is the recommended way of integrating Transloadit and you should use it whenever you allow uploading files from a client. It is not only the best experience for your users, but it also offers the most reliability, because it allows you to replay Assemblies (a button is available on the website's Assembly detail page) in case there was a problem.

If you want to learn more about queues, there is a Queue section in our API docs.

2. Advanced

2.1 Dynamic Assembly Instructions

In addition to template_id, other parameters can be specified as params object. These parameters act as variables to be recursively merged into the Template. For example, assume the following Template:

{
  // the plugin initialization code above this
  steps: {
    encode: {
      use: ":original",
      robot: "/video/encode",
      preset: "iphone"
    },
    store: {
      use: "encode",
      robot: "/s3/store",
      key: "YOUR_AMAZON_S3_KEY",
      secret: "YOUR_AMAZON_S3_SECRET",
      bucket: "YOUR_AMAZON_S3_BUCKET"
    }
  }
}

Additional logic can be merged into the Template by adding a steps key as well:

{
  // the plugin initialization code above this
  auth: { key : "YOUR_TRANSLOADIT_KEY"},
  template_id: "4b62ee4dbb38455d96fe13d972ec3211",
  steps: {
    store: {
      bucket: "other-bucket"
    }
  }
}

This is then merged to create the following Assembly Instructions:

{
  auth: { key: "YOUR_TRANSLOADIT_KEY" },
  template_id: "4b62ee4dbb38455d96fe13d972ec3211",
  steps: {
    encode: {
      use: ":original",
      robot: "/video/encode",
      preset: "iphone"
    },
    store: {
      use: "encode",
      robot: "/s3/store",
      key: "YOUR_AMAZON_S3_KEY",
      secret: "YOUR_AMAZON_S3_SECRET",
      bucket: "other-bucket"
    }
  }
}

Important bucket has a value of "other-bucket" now. These additional params are to be passed to the form using the hidden params field.

If you want to disallow any overriding of Steps, so that a browser could not modify the behavior, of a Template in any way, you can set allow_steps_override to false inside the saved Template.

2.2 Assembly Variables

The following is a list of placeholder variables available to Assembly Instructions. These can be used for any parameter value in any Robot:

Variable Description
${assembly.id}

The ID of the Assembly representing the current upload.

${unique_prefix}

A unique 33-character prefix used to avoid file name collisions, such as "f2/d3eeeb67479f11f8b091b04f6181ad". Please notice the / in the prefix. If you use ${unique_prefix} in the path parameter of the /s3/store Robot for example, then it will create sub-directories in your S3 bucket. This may or may not be desired. Please use ${assembly.id} or ${file.id} if you require a unique prefix without slashes.

${unique_original_prefix}

This is similar to ${unique_prefix}, with the exception that two different encoding results of the same uploaded file (the original file) will have the same prefix value here.

${previous_step.name}

The name of the previous Step that produced the current file.

${file.id}

The ID of the file being processed, which is a 32-character long, unique UUID. It does not contain any periods, slashes or other non-alphanumeric characters.

${file.original_id}

The ID of the original file that a certain file derives from. For example, if you use an import robot to import files and then encode them somehow, the encoding result files will have a ${file.original_id} that matches the ${file.id} of the imported file. For imported files ${file.original_id} equals ${file.id}.

${file.original_basename}

The basename of the original file that a certain file derives from. For example, if you use an import robot to import files and then encode them somehow, the encoding result files will have a ${file.original_basename} that matches the ${file.basename} of the imported file. For imported files ${file.original_basename} equals ${file.basename}.

${file.original_path}

The import path of the original file that a certain file derives from. All of our import robots set ${file.original_path} accordingly. For example, if you use the /s3/import Robot to import files from Amazon S3, the imported files, as well a all files that are derived from them, will have a file.original_path that equals the path to the file on S3, but without the filename. So if the S3 path was "path/to/file.txt", then file.original_path will be "/path/to/". If the path was "/a.txt", ${file.original_path} will be "/". file.original_path will always have sufficient slashes in order for you to safely use it in the path parameter of your export step, like this: "path": "${file.original_path}${file.name}". This is handy if you want to import files from, for example, S3, convert them somehow and store them again on S3 in the same (or similar) file structure.

${file.name}

The name of the file being processed, including the file extension.

${file.url_name}

The name of the file. Any characters other than A-Z a-z 0-9 -_. are replaced with underscores, and spaces are replaced with dashes. This includes the file extension as well.

${file.basename}

The name of the file being processed, without the file extension.

${file.url_basename}

The basename of the file (the file name without the file extension), Any characters other than A-Z a-z 0-9 -_. are replaced with underscores, and spaces are replaced with dashes.

${file.ext}

The file extension.

${file.size}

The file size.

${file.mime}

The file's mime type.

${file.md5hash}

The file's MD5 hash. This is a hash over the file's contents, not only over the file's name.

${file.*}

Any file property available in the final results array, such as ${file.meta.width}. Not all meta keys are available for all file types.

${fields.*}

The form fields submitted together with the upload.
For example, ${fields.myvar} would contain a value of 1 for a form with a
<input type="hidden" name="myvar" value="1" /> field.

Example

To see a good example for the use of Assembly Variables, we can take a look at any of our file export Robots. We will use the /s3/store Robot here, which allows you to store files on Amazon S3.

The Robot has a parameter named path, which controls where on S3 the files will be stored. The default value is "${unique_prefix}/${file.url_name}", which makes the files end up on S3 like "f2/my-file-name.png".

We could, for example, change the parameter's value to "${previous_step.name}/${unique_prefix}/${file.id}.${file.ext}", which would make the files end up like video-step-name/a8/d3eeeb67479f11f8b091b04f6181ad.png.

Please note that Assembly Variables have different levels of uniqueness. For example, ${previous_step.name} is the same for all files that are results of the same Assembly Step. ${file.id} is unique for all files, including results of the same Assembly Step. ${file.ext} can be the same for all files, or can be totally unique, but ${assembly.id}, for example, is the same for all files.

2.3 Form Fields in Instructions

When you set the jQuery SDK's fields option to '*' (or to an object of key value pairs) and submit a form, then the respective form input fields become available in the Assembly as variable names. For example, if a form has a text area named message (using the name attribute), its value could be accessed using ${fields.message} in your path parameter of the store Step, such as in the following example:

{
  auth: { key: "YOUR_TRANSLOADIT_KEY" },
  template_id: "4b62ee4dbb38455d96fe13d972ec3211",
  steps: {
    encode: {
      use: ":original",
      robot: "/video/encode",
      preset: "iphone"
    },
    store: {
      use: "encode",
      robot: "/s3/store",
      key: "YOUR_AMAZON_S3_KEY",
      secret: "YOUR_AMAZON_S3_SECRET",
      bucket: "other-bucket",
      path: "${assembly.id}/${fields.message}/356"
    }
  }
}

A fields key can also be added to the params object to inject variables to the Instructions that are independent of a form:

{
  auth: { key: "YOUR_TRANSLOADIT_KEY" },
  template_id: "4b62ee4dbb38455d96fe13d972ec3211",
  steps: {
    encode: {
      use: ":original",
      robot: "/video/encode",
      preset: "iphone"
    },
    store: {
      use: "encode",
      robot: "/s3/store",
      key: "YOUR_AMAZON_S3_KEY",
      secret: "YOUR_AMAZON_S3_SECRET",
      bucket: "other-bucket",
      path: "${assembly.id}/${fields.message}/356"
    }
  },
  fields: {
    message: "my value"
  }
}

In the example above, variables derived from form fields take precedence over those in the fields key.

2.4 Assembly Notifications

The results of an Assembly can be sent in a POST request to a URL of your choice. This is called an Assembly Notification. It is entirely optional to use these.

The script behind the URL of your choice (the notify_url) needs to respond with a 200 header, otherwise Transloadit assumes the Notification has failed. If that is the case, the Notification is retried up to 5 times over a period of 20 minutes.

Important If you would like to test Assembly Notifications locally, we recommend a service like localtunnel.

The Browser Notifies Your App

When choosing this approach, your visitors will have to wait for both the file uploading and the file conversions to finish.

If you use our jQuery SDK and set its wait parameter to true, the plugin will append the file results to your form as soon as Transloadit has finished processing the upload. It then submits the form to the defined form action.

{
  auth: { key: "YOUR_TRANSLOADIT_KEY" },
  steps: { ... }
}

Unfortunately, this approach has a clear disadvantage: once the file upload is finished, your users must wait for Transloadit to finish all processing, possibly including video encoding and image resizing, before the form is actually submitted to the final destination. This is not usually an issue for image processing, which is very fast in most cases, but definitely harms user experience for video encoding. In this case, consider using Notifications, as explained below.

Important For very specific use-cases, it may help to take a look at the plugin's source code. You can also always ask us to clarify something or assist you with integration.

Letting Transloadit Notify Your App

When choosing this approach, your visitors only wait for the file uploading to finish. They do not have wait for the file conversions to finish.

Notifications are a good way to obtain file results, since they allow you to specify a URL that Transloadit will use to contact you whenever an Assembly is completed.

All Notifications are sent as POST requests, with a field called transloadit. For details about this response format, see the API documentation for the Transloadit response format.

They also contain a signature field, with the signature specifically generated for the Notification. This allows you to verify that it was actually Transloadit sending this Notification. You can learn more about Signature Authentication.

To use Notifications, simply add a notify_url parameter to your params field or your Template:

{
  auth: { key: "YOUR_TRANSLOADIT_KEY" },
  steps: { ... },
  notify_url: "http://example.org/files_ready"
}

One common use case is to include our jQuery SDK, set the wait parameter to false, and use notify_url. This will submit the form to its action attribute as soon as the upload has finished, without waiting for the Transloadit results. Transloadit reports the results to your server once the uploaded files are processed.

Note This provides the best experience, since it prevents users from having to wait unnecessarily when files are uploaded.

The JSON that is sent to your app server will also contain a property called signature. This is the signature that is generated for the Assembly Notification. If you calculate the signature for the whole request yourself with your auth secret, you can verify whether the request is actually from Transloadit (the signatures match) and has not been tampered with (the signatures do not match). For more details regarding signature calculation please read Signature Authentication.

If you would like to test your Assembly Notifications locally, we recommend using services such as ngrok. If this is not possible for you, then you could also take a look at this community project.

If You Cannot Rely on JavaScript Being Enabled

(You can safely ignore this section if you are not going to use our jQuery SDK or other browser integrations like Uppy)

So far we have assumed that you are using the jQuery SDK. But in very rare cases you may not be able to rely on JavaScript being available in the browser.

In this case, you must set your form's action attribute to "http://api2.transloadit.com/assemblies" and you have to provide a redirect_url parameter in your Assembly Instructions. The form will then be submitted to Transloadit and we will then redirect the browser to the redirect_url.

We will also append two GET parameters to that URL: assembly_id and assembly_url. The assembly_id parameter contains the unique ID of your Assembly, and the assembly_url is a Transloadit URL from which the results of the file upload can be obtained. The result is a JSON object that also contains the values of other form fields unrelated to the file upload.

When using Assembly Notifications, i.e you have provided a notify_url, we will still send the conversion result JSON to this notify_url through a POST request.

Important We originally built this approach to avoid the need to have JavaScript enabled in the browser. Times have changed and one can now assume that JavaScript is turned on in the browser.

2.5 Advanced use conditions

The special use parameter can also be assigned an object that specifies additional conditions, which determine the files that are to be used as input for a given Step. The following parameters are currently supported:

Parameter Description

steps

Specifying this has the same effect as providing a string or array for the use parameter.

fields

This is an array of one or more field names (from the upload form). When this is specified, the corresponding Step will only be executed for files submitted through one of the given fields. The field names here correspond to the strings in the name attribute of the HTML file input field tag. This parameter is set to true by default, meaning that all fields are accepted.

Example:

{
  auth: { key: "YOUR_TRANSLOADIT_KEY" },
  steps: {
    encode: {
      robot: "/video/encode",
      use: {
        steps: [ ":original" ],
        fields: [ "file_input_field2" ]
      },
      preset: "iphone"
    }
  }
}

2.6 Signature Authentication

Transloadit uses a very simple authentication system based on JSON and HMAC signatures. Authentication is turned off by default and must be enabled if you want to make use of it.

The Idea in 3 Simple Steps

You get your Auth Key and a private Auth Secret from your API Credentials and follow these Steps:

  1. You decide which Assembly Instructions you want to post to Transloadit.
  2. You add an expiration date and your Auth Key.
  3. You encrypt everything that you will send to Transloadit using your Auth Secret and save the result in a field named signature. You then send that as well.

We will then happily accept your Assembly Steps as long as you POST this before the expiration date.

You can read the following sections for more detailed information about authentication.

Enabling Signature Authentication

To require that all requests against your account are signed:

  1. Go to the API Credentials page under "My Account".
  2. Enable the "Deny requests that do not include a signature or a wrong one" checkbox.
  3. Click the Update button.

Basic Usage

The typical params field for a Transloadit Template or Assembly request is usually as follows:

{
  auth: { key: '23c96d084c744219a2ce156772ec3211' },
  steps: { ... }
}

The auth.key in this example is the "Auth Key" from the API Credentials page.

To sign this request, the additional auth.expires field needs to be added. This field must contain a timestamp in the (near) future, after which the signature will no longer be accepted. Use "YYYY/MM/DD HH:mm:SS+00:00" as the date format, making sure that UTC is used for the timezone. For example:

{
    auth: {
      key: "2b0c45611f6440dfb64611e872ec3211",
      expires: "2009/11/27 16:53:14+00:00"
    },
    steps: { ... }
}

To calculate the signature for this request.

  1. Stringify the above JavaScript object into a JSON string.
  2. Calculate an RFC 2104-compliant HMAC hex signature on the string, with your Auth Secret as the key, and SHA1 as the hash algorithm. Implementation examples for this can be found further down in this section.
  3. Add a signature field to your post request (or as a hidden field in your form), with the signature created in step 2.

Example

Assuming that you are using the following parameters,

{
    auth: {
      expires: "2010/10/19 09:01:20+00:00",
      key: "2b0c45611f6440dfb64611e872ec3211"
    },
    steps: {
      encode: {
        use: ":original",
        robot: "/video/encode"
      }
    }
}

you should sign a JSON string such as the following. Make sure that all quotation marks are in place and that there is no whitespace between JSON keys and values.

{"auth":{"expires":"2010/10/19 09:01:20+00:00","key":"2b0c45611f6440dfb64611e872ec3211"},"steps":{"encode":{"use":":original","robot":"/video/encode"}}}

Given an Auth Secret of d805593620e689465d7da6b8caf2ac7384fdb7e9, the resulting signature would be:

5d349fc1436e2819a912554b1700a16f15b1b91e

Your final request would then look like this:

params=%7B%22auth%22%3A%7B%22key%22%3A%222b0c45611f6440dfb64611e872ec3211%22%2C%22expires%22%3A%222010%2F10%2F19+09%3A01%3A20%2B00%3A00%22%7D%2C%22steps%22%3A%7B%22encode%22%3A%7B%22use%22%3A%22%3Aoriginal%22%2C%22robot%22%3A%22%2Fvideo%2Fencode%22%7D%7D%7D&signature=5d349fc1436e2819a912554b1700a16f15b1b91e

Calculating Signatures When Using Templates

You only have to encrypt the request parameters that you send to Transloadit.

If your params include a template_id, then you do not have to calculate the signature as if all Assembly Instructions from the Template were part of the request parameters.

You only need to calculate the signature for this parameter string:

{ auth: { expires: "2010/10/19 09:01:20+00:00", key: "2b0c45611f6440dfb64611e872ec3211" }, template_id: "YOUR_TRANSLOADIT_TEMPLATE_ID" }

Signature Authentication for Notifications

If you use Notifications, you may want to ensure that only Transloadit can send you data at your notify_url. When a Notification is sent to your notify_url, its POST data includes two fields: transloadit, which contains all the result data, and signature, which contains a signature string calculated for the contents of the transloadit field.

To verify that the POST request actually came from Transloadit, you need to calculate the signature yourself for the entire body of the transloadit field of the Assembly Notification. When the signature in the signature field matches the one you calculate, the request is valid. If not, then the request was tinkered with and should be ignored!

Here is some example Node.js code to calculate the signature yourself to see that the sent signature matches:

Implementations

When you deal with JSON, please keep in mind that your language of choice might escape slashes. That is to say, it might turn occurrences of / into \/. We calculate the signatures on our end with unescaped slashes! Please make sure to remove backslashes from your JSON before calculating its signature.

If you use PHP for example, please check the JSON_UNESCAPED_SLASHES option of the json_encode function.

Ruby

PHP

Node.js

Additional Authentication Options

The auth parameter can also contain the following optional keys, to restrict uploads:

Key Description

referer

A regular expression to match against the HTTP referer of this upload, such as "example\.org". Specify this key to make sure that uploads only come from your domain.

Uploads without a referer will always pass (as they are turned off for some browsers). For details about regular expressions, see Mozilla's RegExp documentation.

max_size

The maximum size an upload can have in bytes, such as 1048576 (1 MB). Specify this to prevent users from uploading excessively large files. When using this key, make sure that it is specified as a hidden max_size form field, since setting max_size in a Template will have no effect.

The file size is checked as soon as the upload is started and if it exceeds the maximum size, the entire upload process is canceled, even if it contains files that do not exceed the max_size limitation.

If you want to just ignore the files that exceed a certain size, but process all others, then please use our file filtering capabilities.

3. Software Development Kits

Here you'll find our officially maintained SDKs. SDKs make it easy to interact with our API, implement our Best Practices, and save you from writing boilerplate. We'll list them alphabetically. Further down you can find community built integrations, not maintained by Transloadit, but often still a valuable source of inspiration.

3.1 Android SDK

The recommended way to integrate Transloadit's file uploading and encoding capabilities with Android is by using our Android SDK.

Documentation

See GitHub for the full documentation.

3.2 iOS SDK

The recommended way to integrate Transloadit's file uploading and encoding capabilities with iOS is by using our iOS SDK.

Documentation

See GitHub for the full documentation.

3.3 jQuery SDK

The recommended way to integrate Transloadit's file uploading and encoding capabilities with jQuery is by using our jQuery SDK.

Install

Note You may also be interested in checking out Uppy, Transloadit's next-gen file uploader for the web.

Simply include the JavaScript asset in your HTML page like so:

<script src="//assets.transloadit.com/js/jquery.transloadit2-v3-latest.js"></script>

To install the deprecated version 2 of the SDK, use the following script tag instead:

<script src="//assets.transloadit.com/js/jquery.transloadit2-v2-latest.js"></script>

This plugin requires jQuery >= 1.9, so be sure to have jQuery loaded on your page before loading this:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Usage

The Transloadit jQuery plugin allows you to

  • show file upload progress,
  • get uploaded results directly without further API queries, and
  • wait for upload processing to complete before redirecting to the result page or calling a callback function.

Assuming a form with the ID "upload-form" (from the minimal integration), the jQuery plugin can be used like this:

<script src="//assets.transloadit.com/js/jquery.transloadit2-v3-latest.js"></script>
<script type="text/javascript">
// We call .transloadit() after the DOM is initialized:
$(function() {
  $('#upload-form').transloadit({
    wait  : true,
    fields: true,

    triggerUploadOnFileSelection: true,

    params : {
      auth  : { key : 'YOUR_TRANSLOADIT_KEY' },
      steps : {
        resize_to_75: {
          robot  : '/image/resize',
          use    : ':original',
          width  : 75,
          height : 75
        },
        // more Steps here
      }
    }
  });
});
</script>

By default, this will display an overlay with a progress bar.

Important Your file input fields must each have a proper name attribute for our jQuery SDK to work properly.

Example

An example use of this plugin can be found in the examples directory.

To run it, simply replace YOUR_TRANSLOADIT_KEY (on the HTML file) with your actual Transloadit key and load the html file on your browser.

Documentation

See GitHub for the full documentation.

3.4 Uppy

The recommended way to integrate Transloadit's file uploading and encoding capabilities with HTML5 is by using our Uppy.

Install

npm install uppy --save

And load it on your webpage like so:

<link href="PATH/TO/NODE_MODULES/uppy/dist/uppy.min.css" rel="stylesheet">
...
<script src="PATH/TO/NODE_MODULES/uppy/dist/uppy.min.js"></script>
...

You may also load Uppy via the unpkg CDN url like so:

<link href="https://unpkg.com/uppy/dist/uppy.min.css" rel="stylesheet">
...
<script src="https://unpkg.com/uppy/dist/uppy.min.js"></script>

This would make the Uppy object available globally as window.Uppy, or simply as Uppy.

Uppy can also be bundled with Browserify or Webpack, and required like so:

const Uppy = require('uppy')
...

This allows you to customize Uppy and create smaller, more focussed bundles leaving out any Plugin you don't need.

Usage

<head>
  <link href="https://unpkg.com/uppy/dist/uppy.min.css" rel="stylesheet"> 
</head>
<body>
  <button id="uppyModalOpener">Open Modal</button>

  <script src="https://unpkg.com/uppy/dist/uppy.min.js"></script>
  <script>
    const Dashboard = Uppy.Dashboard

    const uppy = Uppy.Core({ debug: true, autoProceed: false })
    .use(Uppy.Tus10, { resume: false })
    .use(Uppy.Transloadit, {
      params: {
        auth: {
          key: YOUR_TRANSLOADIT_KEY,
        },
        steps: {
          resize: {
            robot: '/image/resize',
            width: 50,
            height: 50,
          }
        }
      },
      waitForEncoding: true,
    })
    .use(Dashboard, {
      trigger: '#uppyModalOpener',
      target: 'body'
    })
    .use(Uppy.Informer, { target: Dashboard })
    .use(Uppy.Webcam, { target: Dashboard })

    uppy.on('transloadit:result', (stepName, result) => {
      // use transloadit encoding result here.
      console.log('Result here ====>', stepName, result)
    })

    uppy.run()

    document.querySelector('#uppyModalOpener').click()
  </script>
</body>

Example

For fully working examples, take a look at examples/.

Documentation

See the full documentation.

3.5 Node SDK

The recommended way to integrate Transloadit's file uploading and encoding capabilities with Node.js is by using our Node SDK.

Install

Inside your project, type

npm install transloadit --save

If there are no errors, you can start using the module.

Usage

const TransloaditClient = require('transloadit')
const transloadit       = new TransloaditClient({
  authKey   : 'YOUR_TRANSLOADIT_KEY',
  authSecret: 'YOUR_TRANSLOADIT_SECRET'
})

transloadit.addFile('file1', '/PATH/TO/FILE.jpg');

const assemblyOptions = {
  params: {
    template_id: 'YOUR_TEMPLATE_ID'
  }
}

transloadit.createAssembly(assemblyOptions, (err, result) => {
  if (err) {
    throw err
  }

  console.log('✅ success')

  let assemblyId = result.assembly_id

  console.log({
    assemblyId: assemblyId
  })

  transloadit.deleteAssembly(assemblyId, (err) => {
    console.log('✅ deleted')
  })
})

Example

For fully working examples take a look at examples/.

Documentation

See GitHub for the full documentation.

3.6 PHP SDK

The recommended way to integrate Transloadit's file uploading and encoding capabilities with PHP is by using our PHP SDK.

Install

Add the Transloadit PHP SDK as a dependency to your composer.json file:

{
  "require": {
    "transloadit/php-sdk": "dev-master"
  }
}

Consider replacing dev-master with the latest version in order to pin your dependencies.

Install the Composer dependency:

php composer.phar install

Keep your Transloadit account's key & secret key nearby. You can check the API credentials page for these values.

Usage

1. Upload and resize an image from your server

This example demonstrates how you can use the SDK to create an Assembly on your server.

It takes a sample image file, uploads it to Transloadit, and starts a resizing job on it.

<?php
require 'vendor/autoload.php';

use transloadit\Transloadit;

$transloadit = new Transloadit(array(
  'key'    => 'YOUR_TRANSLOADIT_KEY',
  'secret' => 'YOUR_TRANSLOADIT_SECRET',
));

$response = $transloadit->createAssembly(array(
  'files' => array('/PATH/TO/FILE.jpg'),
  'params' => array(
    'steps' => array(
      'resize' => array(
        'robot' => '/image/resize',
        'width' => 200,
        'height' => 100,
      ),
    ),
  ),
));

// Show the results of the assembly we spawned
echo '<pre>';
print_r($response);
echo '</pre>';

2. Create a simple end-user upload form

This example shows you how to create a simple Transloadit upload form that redirects back to your site after the upload is done.

Once the script receives the redirect request, the current status for this Assembly is shown using Transloadit::response().

Note: There is no guarantee that the Assembly has already finished executing by the time the $response is fetched. You should use the notify_url parameter for this.

<?php
require 'vendor/autoload.php';

use transloadit\Transloadit;

$transloadit = new Transloadit(array(
  'key'    => 'YOUR_TRANSLOADIT_KEY',
  'secret' => 'YOUR_TRANSLOADIT_SECRET',
));

// Check if this request is a Transloadit redirect_url notification.
// If so fetch the response and output the current assembly status:
$response = Transloadit::response();
if ($response) {
  echo '<h1>Assembly status:</h1>';
  echo '<pre>';
  print_r($response);
  echo '</pre>';
  exit;
}

// This should work on most environments, but you might have to modify
// this for your particular setup.
$redirectUrl = sprintf(
  'http://%s%s',
  $_SERVER['HTTP_HOST'],
  $_SERVER['REQUEST_URI']
);

// Setup a simple file upload form that resizes an image to 200x100px
echo $transloadit->createAssemblyForm(array(
  'params' => array(
    'steps' => array(
      'resize' => array(
        'robot' => '/image/resize',
        'width' => 200,
        'height' => 100,
      )
    ),
    'redirect_url' => $redirectUrl,
  ),
));
?>
<h1>Pick an image to resize</h1>
<input name="example_upload" type="file">
<input type="submit" value="Upload">
</form>

3. Integrate the jQuery plugin into the previous example

Integrating the jQuery plugin simply means adding a few lines of JavaScript to the previous example. Check the HTML comments below to see what changed.

<?php
require 'vendor/autoload.php';

use transloadit\Transloadit;

$transloadit = new Transloadit(array(
  'key'    => 'YOUR_TRANSLOADIT_KEY',
  'secret' => 'YOUR_TRANSLOADIT_SECRET',
));

$response = Transloadit::response();
if ($response) {
  echo '<h1>Assembly status:</h1>';
  echo '<pre>';
  print_r($response);
  echo '</pre>';
  exit;
}

$redirectUrl = sprintf(
  'http://%s%s',
  $_SERVER['HTTP_HOST'],
  $_SERVER['REQUEST_URI']
);

echo $transloadit->createAssemblyForm(array(
  'params' => array(
    'steps' => array(
      'resize' => array(
        'robot' => '/image/resize',
        'width' => 200,
        'height' => 100,
      )
    ),
    'redirect_url' => $redirectUrl
  )
));
?>
<!--
  Including the jQuery plugin is as simple as adding jQuery and including the
  JS snippet for the plugin. See https://transloadit.com/docs/#jquery-sdk
-->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
  var tlProtocol = (('https:' === document.location.protocol) ? 'https://' : 'http://');
  document.write(unescape("%3Cscript src='" + tlProtocol + "assets.transloadit.com/js/jquery.transloadit2.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
  $(document).ready(function() {
    // Tell the transloadit plugin to bind itself to our form
    $('form').transloadit();
  });
</script>
<!-- Nothing changed below here -->
<h1>Pick an image to resize</h1>
<form>
  <input name="example_upload" type="file">
  <input type="submit" value="Upload">
</form>

Alternatively, check our Uppy, our next-gen file uploader for the web.

4. Fetch the Assembly Status JSON

You can just use the TransloaditRequest class to get the job done easily.

<?php
require 'vendor/autoload.php';
$assemblyId = 'YOUR_ASSEMBLY_ID';

$req = new transloadit\TransloaditRequest();
$req->path = '/assemblies/' . $assemblyId;
$response = $req->execute();

echo '<pre>';
print_r($response);
echo '</pre>';

5. Create an assembly with a template.

This example demonstrates how you can use the SDK to create an Assembly with Templates.

You are expected to create a Template on your Transloadit account dashboard and add the Template ID here.

<?php
require 'vendor/autoload.php';

use transloadit\Transloadit;

$transloadit = new Transloadit(array(
  'key'    => 'YOUR_TRANSLOADIT_KEY',
  'secret' => 'YOUR_TRANSLOADIT_SECRET',
));

$response = $transloadit->createAssembly(array(
  'files' => array('/PATH/TO/FILE.jpg'),
  'params' => array(
    'template_id' => 'YOUR_TEMPLATE_ID'
  ),
));

// Show the results of the assembly we spawned
echo '<pre>';
print_r($response);
echo '</pre>';

Signature Authentication

Signature Authentication is done by the PHP SDK by default internally so you do not need to worry about this :)

Example

For fully working examples take a look at examples/.

Documentation

See GitHub for the full documentation.

3.7 Ruby SDK

The recommended way to integrate Transloadit's file uploading and encoding capabilities with Ruby is by using our Ruby SDK.

Install

gem install transloadit

Usage

To get started, you need to require the 'transloadit' gem:

$ irb -rubygems
>> require 'transloadit'
=> true

Then create a Transloadit instance, which will maintain your authentication credentials and allow us to make requests to the API.

transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_KEY',
  :secret => 'YOUR_TRANSLOADIT_SECRET'
)

1. Resize and store an image

This example demonstrates how you can create an Assembly to resize an image and store the result on Amazon S3.

require 'transloadit'

transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_KEY',
  :secret => 'YOUR_TRANSLOADIT_SECRET'
)

# First, we create two steps: one to resize the image to 320x240, and another to
# store the image in our S3 bucket.
resize = transloadit.step 'resize', '/image/resize',
  :width  => 320,
  :height => 240

store  = transloadit.step 'store', '/s3/store',
  :key    => 'YOUR_AWS_KEY',
  :secret => 'YOUR_AWS_SECRET',
  :bucket => 'YOUR_S3_BUCKET'

# Now that we have the steps, we create an assembly (which is just a request to
# process a file or set of files) and let Transloadit do the rest.
assembly = transloadit.assembly(
  :steps => [ resize, store ]
)

response = assembly.create! open('/PATH/TO/FILE.jpg')

# reloads the response once per second until all processing is finished
response.reload_until_finished!

if response.error?
  # handle error
else
  # handle other cases
  puts response
end

Note: the Assembly method submit! has been deprecated and replaced with create!. The submit! method remains as an alias of create! for backward Compatibility)

When the create! method returns, the file has been uploaded but may not yet be done processing. We can use the returned object to check if processing has completed, or examine other attributes of the request.

# returns the unique API ID of the assembly
response[:assembly_id] # => '9bd733a...'

# returns the API URL endpoint for the assembly
response[:assembly_url] # => 'http://api2.vivian.transloadit.com/assemblies/9bd733a...'

# checks how many bytes were expected / received by transloadit
response[:bytes_expected] # => 92933
response[:bytes_received] # => 92933

# checks if all processing has been finished
response.finished? # => false

# cancels further processing on the assembly
response.cancel! # => true

# checks if processing was succesfully completed
response.completed? # => true

# checks if the processing returned with an error
response.error? # => false

It's important to note that none of these queries are "live" (with the exception of the cancel! method). They all check the response given by the API at the time the Assembly was created. You have to explicitly ask the Assembly to reload its results from the API.

# reloads the response's contents from the REST API
response.reload!

# reloads once per second until all processing is finished, up to number of 
# times specified in :tries option, othewise will raise ReloadLimitReached
response.reload_until_finished! tries: 300 # default is 600

In general, you use hash accessor syntax to query any direct attribute from the response. Methods suffixed by a question mark provide a more readable way of querying state (e.g., assembly.completed? vs. checking the result of assembly[:ok]). Methods suffixed by a bang make a live query against the Transloadit HTTP API.

2. Uploading multiple files

Multiple files can be given to the create! method in order to upload more than one file in the same request. You can also pass a single Step for the steps parameter, without having to wrap it in an Array.

require 'transloadit'

transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_KEY',
  :secret => 'YOUR_TRANSLOADIT_SECRET'
)

assembly = transloadit.assembly(steps: store)

response = assembly.create!(
  open('puppies.jpg'),
  open('kittens.jpg'),
  open('ferrets.jpg')
)

You can also pass an array of files to the create! method. Just unpack the array using the splat * operator.

files = [open('puppies.jpg'), open('kittens.jpg'), open('ferrets.jpg')]
response = assembly.create! *files

3. Parallel Assembly

Transloadit allows you to perform several processing steps in parallel. You simply need to use other Steps. Following their example:

require 'transloadit'

transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_KEY',
  :secret => 'YOUR_TRANSLOADIT_SECRET'
)

encode = transloadit.step 'encode', '/video/encode', { ... }
thumbs = transloadit.step 'thumbs', '/video/thumbs', { ... }
export = transloadit.step 'store',  '/s3/store',     { ... }

export.use [ encode, thumbs ]

transloadit.assembly(
  :steps => [ encode, thumbs, export ]
).create! open('/PATH/TO/FILE.mpg')

You can also tell a step to use the original uploaded file by passing the Symbol :original instead of another step.

Check the YARD documentation for more information on using use.

4. Creating an Assembly with Templates

Transloadit allows you to use custom templates for recurring encoding tasks. In order to use these do the following:

require 'transloadit'

transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_KEY',
  :secret => 'YOUR_TRANSLOADIT_SECRET'
)

transloadit.assembly(
  :template_id => 'YOUR_TEMPLATE_ID'
).create! open('/PATH/TO/FILE.mpg')

You can use your steps together with this template and even use variables. The Transloadit documentation has some nice examples for that.

5. Using fields

Transloadit allows you to submit form field values that you'll get back in the notification. This is quite handy if you want to add additional custom meta data to the upload itself. You can use fields like the following:

require 'transloadit'

transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_KEY',
  :secret => 'YOUR_TRANSLOADIT_SECRET'
)

transloadit.assembly(
  :fields => {
    :tag => 'some_tag_name',
    :field_name => 'field_value'
  }
).create! open('/PATH/TO/FILE.mpg')

6. Notify URL

If you want to be notified when the processing is finished you can provide a Notify URL for the Assembly.

require 'transloadit'

transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_KEY',
  :secret => 'YOUR_TRANSLOADIT_SECRET'
)

transloadit.assembly(
  :notify_url => 'http://example.com/processing_finished'
).create! open('/PATH/TO/FILE.mpg')

Read up more on the Notifications on Transloadit's documentation page

7. Other Assembly methods

Transloadit also provides methods to retrieve/replay Assemblies and their Notifications.

require 'transloadit'

transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_KEY',
  :secret => 'YOUR_TRANSLOADIT_SECRET'
)

assembly = transloadit.assembly

# returns a list of all assemblies
assembly.list

# returns a specific assembly
assembly.get 'YOUR_ASSEMBLY_ID'

# replays a specific assembly
response = assembly.replay 'YOUR_ASSEMBLY_ID'
# should return true if assembly is replaying and false otherwise.
response.replaying?

# returns all assembly notifications
assembly.get_notifications

# replays an assembly notification
assembly.replay_notification 'YOUR_ASSEMBLY_ID'

8. Templates

Transloadit provides a templates api for recurring encoding tasks. Here's how you would create a Template:

require 'transloadit'

transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_KEY',
  :secret => 'YOUR_TRANSLOADIT_SECRET'
)

template = transloadit.template

# creates a new template
template.create(
  :name => 'TEMPLATE_NAME',
  :template => {
    "steps": {
      "encode": {
        "use": ":original",
        "robot": "/video/encode",
        "result": true
      }
    }
  }
)

There are also some other methods to retrieve, update and delete a Template.

require 'transloadit'

transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_KEY',
  :secret => 'YOUR_TRANSLOADIT_SECRET'
)

template = transloadit.template

# returns a list of all templates.
template.list

# returns a specific template.
template.get 'YOUR_TEMPLATE_ID'

# updates the template whose id is specified.
template.update(
  'YOUR_TEMPLATE_ID',
  :name => 'CHANGED_TEMPLATE_NAME',
  :template => {
    :steps => {
      :encode => {
        :use => ':original',
        :robot => '/video/merge'
      }
    }
  }
)

# deletes a specific template
template.delete 'YOUR_TEMPLATE_ID'

9. Getting Bill reports

If you want to retrieve your Transloadit account billing report for a particular month and year you can use the bill method passing the required month and year like the following:

require 'transloadit'

transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_KEY',
  :secret => 'YOUR_TRANSLOADIT_SECRET'
)

# returns bill report for February, 2016.
transloadit.bill(2, 2016)

Not specifying the month or year would default to the current month or year.

10. Rate limits

Transloadit enforces rate limits to guarantee that no customers are adversely affected by the usage of any given customer. See Rate Limiting.

While creating an Assembly, if a rate limit error is received, by default, 2 more attempts would be made for a successful response. If after these attempts the rate limit error persists, a RateLimitReached exception will be raised.

To change the number of attempts that will be made when creating an Assembly, you may pass the tries option to your Assembly like so.

require 'transloadit'

transloadit = Transloadit.new(
  :key    => 'YOUR_TRANSLOADIT_KEY',
  :secret => 'YOUR_TRANSLOADIT_SECRET'
)

# would make one extra attempt after a failed attempt.
transloadit.assembly(:tries => 2).create! open('/PATH/TO/FILE.mpg')

# Would make no attempt at all. Your request would not be sent.
transloadit.assembly(:tries => 0).create! open('/PATH/TO/FILE.mpg')

Example

A small sample tutorial of using the Transloadit ruby-sdk to optimize an image, encode MP3 audio, add ID3 tags, and more can be found here.

Documentation

Up-to-date YARD documentation is automatically generated. You can view the docs for the released gem or for the latest git master.

3.8 Python SDK

The recommended way to integrate Transloadit's file uploading and encoding capabilities with Python is by using our Python SDK.

Install

pip install transloadit

Usage

from transloadit import client

tl = client.Transloadit('TRANSLOADIT_KEY', 'TRANSLOADIT_SECRET')
assembly = tl.new_assembly()
assembly.add_file(open('PATH/TO/FILE.jpg', 'rb'))
assembly.add_step('resize', '/image/resize', {'width': 70, 'height': 70})
assembly_response = assembly.create(retries=5, wait=True)

print assembly_response.data.get('assembly_id')

# or
print assembly_response.data['assembly_id']

Documentation

See url here for full API documentation.

3.9 Rails SDK

The recommended way to integrate Transloadit's file uploading and encoding capabilities with Rails is by using our Rails SDK.

Install

$ gem install transloadit-rails

or add the transloadit-rails Gem to your Rails project's Gemfile and update your bundle.

$ echo "gem 'transloadit-rails'" >> Gemfile
$ bundle install

After installation you need to run the transloadit:install generator to complete the setup.

$ rails g transloadit:install

Usage

Refer to the Templates (which you have set in the config) with the transloadit helper.

<%= form_for :upload, :html => { :id => 'upload' } do |form| %>
  <%= transloadit :s3_store %>
  <%= form.label      :file, 'File to upload' %>
  <%= form.file_field :file %>
  <%= form.submit %>
<% end %>

<%= javascript_include_tag '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' %>
<%= transloadit_jquerify :upload %>

This requires jQuery, and loads the Transloadit jQuery plugin. Be sure to exclude the <%= javascript_include_tag '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' %> tag if you already have jQuery loaded.

JavaScript also ensures your form is encoded as multipart/form-data.

If you want to use the automatic transloadit parameter decoding, you have to include the Transloadit::Rails::ParamsDecoder module into your controller

class YourController
  include Transloadit::Rails::ParamsDecoder
end

that way the param[:transloadit] is automatically decoded for you, if it exists

Note Since it's still very young, the Transloadit Rails SDK does not include batteries for it yet, but if you're looking for a jQuery-less integration, check out Uppy, our next-gen file uploader for the web.

Example

An example rails application following the tutorial above can be found in the examples directory.

Documentation

See GitHub for the full documentation.

3.10 Go SDK

The recommended way to integrate Transloadit's file uploading and encoding capabilities with Go is by using our Go SDK.

Install

go get gopkg.in/transloadit/go-sdk.v1

The Go SDK requires Go 1.7 or higher.

Usage

package main

import (
	"context"
	"fmt"

	"gopkg.in/transloadit/go-sdk.v1"
)

func main() {
	// Create client
	options := transloadit.DefaultConfig
	options.AuthKey = "YOUR_TRANSLOADIT_KEY"
	options.AuthSecret = "YOUR_TRANSLOADIT_SECRET"
	client := transloadit.NewClient(options)

	// Initialize new assembly
	assembly := transloadit.NewAssembly()

	// Add a file to upload
	assembly.AddFile("image", "/PATH/TO/FILE.jpg")

	// Add instructions, e.g. resize image to 75x75px
	assembly.AddStep("resize", map[string]interface{}{
		"robot":           "/image/resize",
		"width":           75,
		"height":          75,
		"resize_strategy": "pad",
		"background":      "#000000",
	})

	// Start the upload
	info, err := client.StartAssembly(context.Background(), assembly)
	if err != nil {
		panic(err)
	}

	// All files have now been uploaded and the assembly has started but no
	// results are available yet since the conversion has not finished.
	// WaitForAssembly provides functionality for polling until the assembly
	// has ended.
	info, err = client.WaitForAssembly(context.Background(), info)
	if err != nil {
		panic(err)
	}

	fmt.Printf("You can view the result at: %s\n", info.Results["resize"][0].SSLURL)
}

Example

For fully working examples on how to use templates, non-blocking processing and more, take a look at examples/.

Documentation

See Godoc for full API documentation.

3.11 Java SDK

The recommended way to integrate Transloadit's file uploading and encoding capabilities with Java is by using our Java SDK.

Install

The JARs can be downloaded manually from our Bintray project, or can be installed from the Maven and Jcenter repositories.

Gradle:

compile 'com.transloadit.sdk:transloadit:0.0.3'

Maven:

<dependency>
  <groupId>com.transloadit.sdk</groupId>
  <artifactId>transloadit</artifactId>
  <version>0.0.3</version>
</dependency>

Usage

All interactions with the SDK begin with the com.transloadit.sdk.Transloadit class.

Create an Assembly

To create an assembly, you use the newAssembly method.

import com.transloadit.sdk.Transloadit;
import com.transloadit.sdk.exceptions.LocalOperationException;
import com.transloadit.sdk.exceptions.RequestException;
import com.transloadit.sdk.response.AssemblyResponse;

import java.io.File;
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        Transloadit transloadit = new Transloadit("YOUR_TRANSLOADIT_KEY", "YOUR_TRANSLOADIT_SECRET");

        Assembly assembly = transloadit.newAssembly();

        Map<String, Object> stepOptions = new HashMap<>();
        stepOptions.put("width", 75);
        stepOptions.put("height", 75);
        assembly.addStep("resize", "/image/resize", stepOptions);

        assembly.addFile(new File("PATH/TO/FILE.jpg"));
        try {
            AssemblyResponse response = assembly.save();

            // wait for assembly to finish executing.
            while (!response.isFinished()) {
                response = transloadit.getAssemblyByUrl(response.getSslUrl());
            }

            System.out.println(response.getId());
            System.out.println(response.getUrl());
            System.out.println(response.json());

        } catch (RequestException | LocalOperationException e) {
            // handle exception here
        }
    }
}

Get an Assembly

The method, getAssembly, retrieves the JSON status of an assembly identified by the given assembly_Id.

import com.transloadit.sdk.Transloadit;
import com.transloadit.sdk.exceptions.LocalOperationException;
import com.transloadit.sdk.exceptions.RequestException;
import com.transloadit.sdk.response.AssemblyResponse;

public class Main {
    public static void main(String[] args) {
        Transloadit transloadit = new Transloadit("YOUR_TRANSLOADIT_KEY", "YOUR_TRANSLOADIT_SECRET");

        try {
            AssemblyResponse response = transloadit.getAssembly("ASSEMBLY_ID");

            System.out.println(response.getUrl());
            System.out.println(response.json());

        } catch (RequestException | LocalOperationException e) {
            // handle exception here
        }
    }
}

You may also get an assembly by url with the getAssemblyByUrl method.

    AssemblyResponse response = transloadit.getAssemblyByUrl("ASSEMBLY_URL");

Cancel an Assembly

To cancel an executing assembly, you use the cancelAssembly method, passing the assembly id as a parameter.

import com.transloadit.sdk.Transloadit;
import com.transloadit.sdk.exceptions.LocalOperationException;
import com.transloadit.sdk.exceptions.RequestException;
import com.transloadit.sdk.response.AssemblyResponse;

public class Main {
    public static void main(String[] args) {
        Transloadit transloadit = new Transloadit("YOUR_TRANSLOADIT_KEY", "YOUR_TRANSLOADIT_SECRET");

        try {
            AssemblyResponse response = transloadit.cancelAssembly("ASSEMBLY_ID");

            System.out.println(response.isCancelled()); // prints true
        } catch (RequestException | LocalOperationException e) {
            // handle exception here
        }
    }
}

List Assemblies

The method, listAssemblies, retrieves an array of assemblies according to the given options. Valid options can be page, pagesize, type, fromdate and todate. Please consult the Transloadit API docs for details.

import com.transloadit.sdk.Transloadit;
import com.transloadit.sdk.exceptions.LocalOperationException;
import com.transloadit.sdk.exceptions.RequestException;
import com.transloadit.sdk.response.ListResponse;

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        Transloadit transloadit = new Transloadit("YOUR_TRANSLOADIT_KEY", "YOUR_TRANSLOADIT_SECRET");

        try {
            Map<String, Object> options = new HashMap<>();
            options.put("pagesize", 10);
            ListResponse response = transloadit.listAssemblies(options);

            System.out.println(response.size());  // number of assemblies on the list.
            System.out.println(response.getItems());  // returns an iterable json array

        } catch (RequestException | LocalOperationException e) {
            // handle exception here
        }
    }
}

Create a Template

To create a new template, you use the newTemplate method, passing the template name as a parameter.

import com.transloadit.sdk.Transloadit;
import com.transloadit.sdk.exceptions.LocalOperationException;
import com.transloadit.sdk.exceptions.RequestException;
import com.transloadit.sdk.response.Response;

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        Transloadit transloadit = new Transloadit("YOUR_TRANSLOADIT_KEY", "YOUR_TRANSLOADIT_SECRET");

        Template template = transloadit.newTemplate("MY_TEMPLATE_NAME");

        Map<String, Object> resizeOptions = new HashMap<>();
        resizeOptions.put("width", 75);
        resizeOptions.put("height", 75);

        Map<String, Object> optimizeOptions = new HashMap<>();
        optimizeOptions.put("use", ":original");

        template.addStep("resize", "/image/resize", resizeOptions);
        template.addStep("resize", "/image/optimize", optimizeOptions);

        try {
            Response response = template.save();

            System.out.println(response.json());
            System.out.println(response.json().getString("id")); // gets the template id.
        } catch (RequestException | LocalOperationException e) {
            // handle exception here
        }
    }
}

Update a Template

To update a template, you use the updateTemplate method, passing the template id and options to update as a parameters.

import com.transloadit.sdk.Transloadit;
import com.transloadit.sdk.Steps;
import com.transloadit.sdk.exceptions.LocalOperationException;
import com.transloadit.sdk.exceptions.RequestException;
import com.transloadit.sdk.response.Response;

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        Transloadit transloadit = new Transloadit("YOUR_TRANSLOADIT_KEY", "YOUR_TRANSLOADIT_SECRET");

        Steps steps = new Steps();

        Map<String, Object> stepOptions = new HashMap<>();
        stepOptions.put("width", 150);
        stepOptions.put("height", 150);
        steps.addStep("resize", "/image/resize", stepOptions);

        Map<String, Object> templateOptions = new HashMap<>();
        templateOptions.put("steps", steps.toMap());
        templateOptions.put("name", "MY_NEW_TEMPLATE_NAME");

        try {
            Response response = transloadit.updateTemplate("TEMPLATE_ID", templateOptions);

        } catch (RequestException | LocalOperationException e) {
            // handle exception here
        }
    }
}

Delete a Template

To delete a template, you use the deleteTemplate method, passing the template id as a parameter.

import com.transloadit.sdk.Transloadit;
import com.transloadit.sdk.exceptions.LocalOperationException;
import com.transloadit.sdk.exceptions.RequestException;
import com.transloadit.sdk.response.Response;

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        Transloadit transloadit = new Transloadit("YOUR_TRANSLOADIT_KEY", "YOUR_TRANSLOADIT_SECRET");

        try {
            Response response = transloadit.deleteTemplate("TEMPLATE_ID");

        } catch (RequestException | LocalOperationException e) {
            // handle exception here
        }
    }
}

List Templates

To get a list of all templates under your account, you use the listTemplates method.

import com.transloadit.sdk.Transloadit;
import com.transloadit.sdk.exceptions.LocalOperationException;
import com.transloadit.sdk.exceptions.RequestException;
import com.transloadit.sdk.response.ListResponse;

public class Main {
    public static void main(String[] args) {
        Transloadit transloadit = new Transloadit("YOUR_TRANSLOADIT_KEY", "YOUR_TRANSLOADIT_SECRET");

        try {
            ListResponse response = transloadit.listTemplates();

            System.out.println(response.size());  // number of assemblies on the list.
            System.out.println(response.getItems());  // returns an iterable json array

        } catch (RequestException | LocalOperationException e) {
            // handle exception here
        }
    }
}

Get a template

To get a particular template, you use the getTemplate method, passing the template id as a parameter.

import com.transloadit.sdk.Transloadit;
import com.transloadit.sdk.exceptions.LocalOperationException;
import com.transloadit.sdk.exceptions.RequestException;
import com.transloadit.sdk.response.Response;

public class Main {
    public static void main(String[] args) {
        Transloadit transloadit = new Transloadit("YOUR_TRANSLOADIT_KEY", "YOUR_TRANSLOADIT_SECRET");

        try {
            AssemblyResponse response = transloadit.getTemplate("TEMPLATE_ID");
            System.out.println(response.json());
        } catch (RequestException | LocalOperationException e) {
            // handle exception here
        }
    }
}

Get bill

To get your account billing details for a particular month, you use the getBill method, passing the month and year as parameters.

import com.transloadit.sdk.Transloadit;
import com.transloadit.sdk.exceptions.LocalOperationException;
import com.transloadit.sdk.exceptions.RequestException;
import com.transloadit.sdk.response.Response;

public class Main {
    public static void main(String[] args) {
        Transloadit transloadit = new Transloadit("YOUR_TRANSLOADIT_KEY", "YOUR_TRANSLOADIT_SECRET");

        try {
            ListResponse response = transloadit.getBill(3, 2017);

            System.out.println(response.json());
        } catch (RequestException | LocalOperationException e) {
            // handle exception here
        }
    }
}

Example

For fully working examples take a look at examples/.

Documentation

See Javadoc for full API documentation.

3.12 Transloadify

The recommended way to integrate Transloadit's file uploading and encoding capabilities with CLI is by using our Transloadify.

Install

$ npm install -g transloadify

Usage

Transloadify needs Transloadit API authentication information. It looks for it in the environment variables TRANSLOADIT_KEY and TRANSLOADIT_SECRET. Check the API credentials page for these values.

See transloadify --help for complete usage instructions.

Processing media

Transloadify uses the Transloadit API. Transloadit allows you to process media in the cloud by creating Assemblies. An Assembly in an execution of processing instructions on an uploaded file. The simplest way to create Assemblies using Transloadify is to put the processing instructions (called Assembly Instructions) in a JSON file and give it to Transloadify using the --steps option. Transloadify will then upload whatever is passed to it via standard in, and output the result file to standard out.

$ transloadify --steps steps.json < input.jpg > output.jpg

Transloadit supports Templates which are Assembly Instructions stored in the cloud. Templates can be created and managed through Transloadify using the templates commands. If you have a Template that you would like to use to process media, you can specify it with the --template option instead of specifying a --steps.

$ transloadify --template TEMPLATE_ID < input.jpg > output.jpg

If your Template expects certain custom fields to be set, those can be specified using the --field option.

$ transloadify --template TEMPLATE_ID --field size=100 < input.jpg > output.jpg

Rather than use STDIN and STDOUT, you can also pass files to Transloadify using the --input and --output flags. These flags are also more flexible than standard IO because they can take directories, to process media in batch, optionally traversing subdirectories with the --recursive option.

$ transloadify --template TEMPLATE_ID --field size=100 \
    --input images --recursive --output thumbs

Transloadify also has the option to watch inputs for changes, using the --watch option, and reprocessing them whenever a change is detected.

$ transloadify --template TEMPLATE_ID --field size=100 \
    --input images --recursive --output thumbs --watch

All of these flags support shortened versions, to avoid invocations getting too long. See transloadify assemblies create --help for details. The above can be shortened to:

$ transloadify -tTEMPLATE_ID -fsize=100 -i images -o thumbs -wr

Assemblies

The transloadify assemblies subcommand lets you manage assemblies. Using transloadify you can create, cancel, replay, list and fetch Assembly Statuses. See transloadify assemblies --help for a list of available actions, and transloadify assemblies ACTION --help for specific action documentation.

Creation

The usage described in Processing media implicitly uses the transloadify assemblies create command, which has the same behavior as the bare transloadify command.

Listing

You can use Transloadify to list assemblies associated with the account, optionally filtered by date and keywords. For instance:

$ transloadify assemblies list --after 2016-11-08

See transloadify assemblies list --help for a list of accepted options.

One use-case is to recover failed assemblies once the issue has been resolved. If a Template definition contained an error that caused Assemblies to fail, you can salvage them by fixing the Template and using an invocation like this, using the jq JSON utility.

$ transloadify assemblies list --json --after "$AFFECTED_DATE" \
  | jq -r 'select(.error) | .id' \
  | xargs transloadify assemblies get --json \
  | jq -r 'select(.template_id == "'$AFFECTED_TEMPLATE'") | .assembly_id' \
  | xargs transloadify assemblies replay --reparse-template

Templates

transloadify templates is used to create and manage templates. transloadify templates --help gives a list of supported actions.

Modification

transloadify templates modify will read new Template contents from standard in if no file is specified. If you just want to rename a Template using the --name option, the command will ignore empty input:

$ transloadify templates rename $TEMPLATE_ID --name my_template < /dev/null

Assembly Notifications

Support for listing and replaying Assembly Notifications is provided by transloadify assembly-notifications list and transloadify assembly-notifications replay respectively.

Listing

transloadify assembly-notifcations list can list, optionally filtered by whether they succeeded or failed, either all Notifications associated with an account, or for a given Assembly. If you would like to see Notifications for a list of Assemblies, it must be called for each one individually.

$ transloadify assemblies list --after 2016-11-08 \
  | xargs -n1 transloadify assembly-notifications list

Bills

Monthly billing information can be fetched with transloadify bills get YYYY-MM.... By default only the total charge is output, but more detailed information can be displayed in JSON format with the --json flag.

$ transloadify bills get 2016-11 --json

Tips

  • Command names have aliases, the following are interchangeable
    • assemblies, assembly, a
    • templates, template, t
    • assembly-notifications, assembly-notification, notifications, notification, n
    • bills, bill, b
    • create, new, c
    • delete, cancel, d
    • modify, edit, alter, m
    • replay, r
    • list, l
    • get, info, view, display, g
  • All output, from any command, can also be provided in JSON format using the --json flag

Example

An example script written to add watermark to videos can be found here examples/.

Documentation

See GitHub for the full documentation.

3.13 Heroku Addon

The recommended way to integrate Transloadit's file uploading and encoding capabilities with Heroku is by using our Heroku Addon.

Install

Transloadit can be attached to a Heroku application via the CLI:

$ heroku addons:add transloadit
-----> Adding transloadit to sharp-mountain-4005... done, v18 (free)
A list of all plans available can be found here.

Once Transloadit has been added the TRANSLOADIT_AUTH_KEY and TRANSLOADIT_SECRET_KEY settings will be available in the app configuration and will contain the credentials needed to authenticate to the Transloadit API. This can be confirmed using the heroku config:get command.

$ heroku config:get TRANSLOADIT_AUTH_KEY
4bba21cf6d744fd1aeef0f0b72ec3212

Usage

With your TRANSLOADIT_AUTH_KEY and TRANSLOADIT_SECRET_KEY in place you can now integrate it with any of our SDKs corresponding to your project. Here's a list of our SDKs:

Using with Ruby (Uses our Ruby SDK)

Verify that the TRANSLOADIT_AUTH_KEY and TRANSLOADIT_SECRET_KEY variables are set.

Ruby applications need to add the following entry into their Gemfile specifying the Transloadit client library.

gem 'transloadit'

Then update application dependencies with bundler.

$ bundle install

Finally re-deploy your application.

$ git add .
$ git commit -a -m "add transloadit instrumentation"
$ git push heroku master

First encoding job

After installing the transloadit Gem and deploying your app you can start talking to the Transloadit API:

require 'transloadit'

puts "Resizing lolcat.jpg on #{ENV['TRANSLOADIT_URL']}"

transloadit = Transloadit.new(
  :service => ENV['TRANSLOADIT_URL'],
  :key     => ENV['TRANSLOADIT_AUTH_KEY'],
  :secret  => ENV['TRANSLOADIT_SECRET_KEY']
)

resize = transloadit.step 'resize', '/image/resize',
  :width  => 320,
  :height => 240

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

response = assembly.submit! open('lolcat.jpg')

# loop until processing is finished
until response.finished?
  sleep 1; response.reload! # you'll want to implement a timeout in your production app
end

if response.error?
 # handle error
else
 # handle other cases
end

Using with Ruby on Rails (Uses our Rails SDK)

Here we'll show how to use Transloadit in a freshly setup Rails project and Heroku app.

If you haven't already done so, go ahead and install Rails.

$ gem install rdoc rails

With Rails installed, let's create a new app called 'transloku'.

$ rails new transloku
$ cd transloku

In order to use Transloadit in this app, we need to add the Gem to our Gemfile and bundle things up.

Remove sqlite3 from your Gemfile

$ echo "ruby '2.0.0'" >> Gemfile
$ echo "gem 'transloadit-rails'" >> Gemfile
$ echo "gem 'pg'" >> Gemfile
$ bundle install

With that in place, it's time to generate our Transloadit configuration, as well as a basic UploadsController and a dummy Upload model.

$ rails g transloadit:install
$ rails g controller uploads new create
$ rails g model upload
$ rake  db:migrate

The controller generator we just executed has probably put two GET routes into your config/routes.rb. We don't want those, so lets go ahead an overwrite them with this.

Transloku::Application.routes.draw do
  resources :uploads
end

Next we need to configure our config/transloadit.yml file. For this tutorial, just put in your credentials, and define an image resize step as indicated below:

auth:
  key     : <%= ENV['TRANSLOADIT_AUTH_KEY'] %>
  secret  : <%= ENV['TRANSLOADIT_SECRET_KEY'] %>

templates:
  image_resize:
    steps:
      resize:
        robot : '/image/resize'
        format: 'jpg'
        width : 320
        height: 200

Note that we encourage you to enable authentication in your Transloadit Account and put your secret into the config/transloadit.yml to have your requests signed.

Make your config/database.yml look like this:

development:
  adapter: postgresql
  encoding: unicode
  database: transloku_development
  pool: 5
  password:

test:
  adapter: postgresql
  encoding: unicode
  database: transloku_test
  pool: 5
  password:

production:
  adapter: postgresql
  encoding: unicode
  database: transloku_production
  pool: 5
  password:

Alright, time to create our upload form. In order to do that, please open app/views/uploads/new.html.erb, and put the following code in:

<%= javascript_include_tag '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' %>

<h1>Upload an image</h1>
<%= form_for Upload.new, :html => { :id => 'upload' } do |form| %>
  <%= transloadit :image_resize %>
  <%= form.label      :file, 'File to upload' %>
  <%= form.file_field :file %>
  <%= form.submit %>
<% end %>

<%= transloadit_jquerify :upload, :wait => true %>

With this in place, we can modify the app/views/uploads/create.html.erb view to render the uploaded and resized image:

<h1>Resized upload image</h1>
<%= image_tag params[:transloadit][:results][:resize].first[:url] %>

In order to use the transloadit params in your controller and views you have to include the ParamsDecoder into your controller. Let's do that for our UploadsController.

Open up app/controllers/uploads_controller.rb and adapt it like that:

class UploadsController < ApplicationController
  include Transloadit::Rails::ParamsDecoder

  def new
  end

  def create
  end
end

That's it. If you've followed the steps closely, you should now be able to try your first upload. Don't forget do start your rails server first:

$ rails server

Then go to http://localhost:3000/uploads/new, and upload an image. If you did everything right, you should see the uploaded and resized file as soon as the upload finishes.

All looking sharp? Let's publish this to Heroku

$ git init
$ git add .
$ git commit -m "init"
$ heroku login
$ heroku create
$ heroku addons:add transloadit
$ heroku config:get TRANSLOADIT_AUTH_KEY
$ git push heroku master
$ heroku run rake db:migrate
$ heroku open && heroku logs --tail

Point your browser to /uploads/new

Using with any Language

Instead of talking server-to-server, your website visitors can directly upload to Transloadit's specialized upload servers, so in theory there's no need for serverside languages.

The easiest way to accomplish this would be to to include our jQuery SDK in your HTML.

It includes a Twitter Bootstrap compatible progress bar, and it saves you development time having to handle the file uploads yourself, and then pushing it to our API.

<script type="text/javascript" src="//assets.transloadit.com/js/jquery.transloadit2-v3-latest.js"></script>
<script type="text/javascript">
   // We call .transloadit() after the DOM is initialized:
   $(function() {
     $('#MyForm').transloadit();
   });
</script>

Alternatively, check our Uppy, our next-gen file uploader for the web.

Documentation

See GitHub for the full documentation.

4 Community Projects

4.1 Community Projects

The following is a list of projects created by community members, for community members.

Did you see something cool that could be useful to others in the community? Please get in touch and we will list your project here.

4.2 Example Applications

Image Cropping Tool

In this example application you upload an image and then select a cropping area using drag and drop. Submitting the form will crop the uploaded image via Transloadit and give the result image back to you.

You can find a live demo and the source code here.

Video Preview Image Chooser

In this example application you upload a video and then have to option to select a cover image for the video from 10 thumbnails that are extracted from the video. Your choice will be resized into several formats. The uploaded video will also be encoded into several different web formats.

You can find a live demo and the source code here.