@transloadit/jquery-sdk
v3.3.4
Published
[![Build Status](https://travis-ci.org/transloadit/jquery-sdk.svg)](https://travis-ci.org/transloadit/jquery-sdk)
Downloads
6
Readme
Warning: We recommend using Uppy instead of the jQuery SDK these days.
Transloadit jQuery SDK
A jQuery Integration for Transloadit's file uploading and encoding service
Intro
Transloadit is a service that helps you handle file uploads, resize, crop and watermark your images, make GIFs, transcode your videos, extract thumbnails, generate audio waveforms, and so much more. In short, Transloadit is the Swiss Army Knife for your files.
This is a jQuery SDK to make it easy to talk to the Transloadit REST API. It supports resumable file uploads out of the box including a modal box with a progress bar, drag and drop support and several other nice things. :)
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. jQuery >= 1.9 is also required.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//assets.transloadit.com/js/jquery.transloadit2-v3-latest.js"></script>
How does it work
You have an HTML form on your page like this one for example:
<form id="upload-form" action="/uploads" enctype="multipart/form-data" method="POST">
<input type="file" name="my_file" multiple="multiple" />
<div class="transloadit-drop-area">Drag and drop files here</div>
<div class="transloadit-file-preview-area"></div>
<input type="text" name="album_id" value="foo_id" />
<input type="submit" value="Upload">
</form>
By attaching the jQuery SDK to the form you enable uploading functionality on the form:
$('#upload-form').transloadit({
wait: true,
triggerUploadOnFileSelection: true,
params : {
auth : { key : 'YOUR_TRANSLOADIT_KEY' },
template_id : 'YOUR_TEMPLATE_ID'
}
});
Once you select some files over the file input field (or the drag and drop area) a modal will appear that will upload your fils.
The wait
parameter set to true
instruct the SDK to wait for all transcoding to finish. Once it's finished it will attach a long JSON
string to a hidden textarea in your form.
You can then submit the form as you normally would. On your backend you have an extra POST field named "transloadit"
then in the payload including JSON with information about all uploads and transcoding results, their meta data and the URLs to them.
It's that simple. :)
Version 3
Changes from version 2 to version 3:
BC Breaking changes:
- The onExecuting() callback does not have the array of
uploads
anymore. Please use theonUpload
callback to track received uploads. - The onUpload() and onResult() callbacks no longer receive the assembly object as a parameter.
- The formData parameter has been removed, because all uploads use XHR now. This will only break BC for you if you used formData: customFormDataObj. In that case you should add the contents of your custom form data as hidden input fields to the form now.
- Several new translations have been added for which you would need to add a translation in case you run on a custom locale. Please check "How to add your own localization / other language strings" at the bottom of this page for details.
- There is a new
translations
parameter now that must be used to get your custom locale working.
Non-BC Breaking Changes and new features:
- There is now support for resumable file uploads! It works out of the box, you do not need to change anything for it.
- Performance has been improved in all areas of the plugin.
- Drag and Drop support has been added.
- Support for file preview lists has been added.
- All options related to polling have been removed.
- There is now a lot less network traffic for assembly status updates.
- There is now the ability to not wait for file upload meta data anymore, which is a big speed improvement. This change was also backported to the last version in the 2.x series.
- There is now a new parameter "maxNumberOfUploadedFiles", with which you can set a limit to the number of uploaded files.
- There are two new callbacks implemented: onDisconnect() and onReconnect()
Version 2 of the plugin is CEASEED TO EXIST on September 30, 2017. Please upgrade to version 3 as soon as possible.
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.
Specifying Assembly Instructions in the Form
Instead of using the plugin's params
parameter, 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, and also when you want to add Signature authentication 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="{"auth":{"key":"YOUR_TRANSLOADIT_KEY"},"steps":{"resize_to_75":{"robot":"\/image\/resize","use":":original","width":75,"height":75}}}" />
<input type="file" name="my_file" />
<input type="submit" value="Upload">
</form>
Both ways of adding the Assembly Instructions are valid. When you upload a file you should see the same result.
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.
Releases
We have one magic release:
jquery.transloadit-v3-latest.js
This is always the latest version of the v3 branch and is the recommended version to use. https://assets.transloadit.com/js/jquery.transloadit2-v3-latest.jsYou can also pin specific versions via: https://assets.transloadit.com/js/jquery.transloadit2-v3.0.0.js. Remember that it then becomes your responsibility to keep track of security and performance upgrades in our releases.
Callbacks
These can be added as parameters to the .transloadit()
call like so:
<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({
onStart: function(assembly) {
console.log('>> Uploading has started!');
},
onExecuting: function(assembly) {
console.log('>> Transcoding has started!');
},
});
});
Each upload here has an ID field. You can map that back to the original_id field of results on the onResult callback.
Please set requireUploadMetaData to true if you use this callback.
Results here contain a key original_id, which maps them back to the ID of the originally uploaded file's ID.
Parameters
These can be added as parameters to the .transloadit()
call like so:
<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,
region: 'eu-west-1'
});
});
However, if you set wait to false, the onSuccess callback is fired as soon as the uploading is finished. The uploads array in the passed assembly object will be empty in this case. If you need this uploads array to be populated, set this option to true.
This option is false by default to fire the onSuccess callback as soon as possible to increase perceived performance.
An object of Assembly instructions that should be executed. For examples please check the minimal integration. This is null by default, which means the instructions are read from the hidden input field named params.
Here is an example:
Please make sure the signature is calculated in your back-end code, so that your Transloadit Auth Secret is not exposed in your public JavaScript code!
A CSS selector that specifies the form fields to be sent to Transloadit. This is false by default, which means no form fields are submitted with an upload.
For example:
If you would like to only send some fields, set this parameter to a CSS selector string matching the fields to be sent:
If you would like to send all form fields, set this to true:
You can also set this to an object of key/value pairs:
The fields that you send here will be available as ${fields.*} variables in your Assembly instructions. Learn more about that here.
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 help you with integration.
Drag and drop
To enable drag and drop please add a div to your form like as follows:
<div class="transloadit-drop-area" data-name="files">Please drag and drop files here</div>
You can change the text of course and also the value of the data-name attribute. If you do not have the data-name attribute set, we will default it to "files".
This will create a drag and drop area with some default CSS in your form. This is the default CSS for it - feel free to overwrite it in your own CSS files:
.transloadit-drop-area {
padding: 5px;
width: 200px;
height: 75px;
border: 2px dashed #ccc;
}
.transloadit-drop-area.hover {
border: 2px dashed #0af;
}
File preview areas
File preview areas are lists that are automatically populated with the files that will be part of the upload. The user can then review the list prior to the upload and remove some files again if he or she so wishes.
To enable file preview areas, please add a div to your form like as follows:
<div class="transloadit-file-preview-area"></div>
This will create a file preview area with some default CSS in your form. This is the default CSS for it - feel free to overwrite it in your own CSS files:
.transloadit-file-preview-area {
margin: 10px 0;
padding: 5px;
width: 300px;
height: 100px;
overflow-y: auto;
border: 1px solid #ccc;
}
.transloadit-file-preview-area ul {
margin: 0!important;
padding: 0!important;
}
.transloadit-file-preview-area li {
border-top: 1px solid #ddd;
list-style-type: none;
display: inline-block;
width: 100%;
height: 12px;
padding: 1px 3px 3px 3px;
font-size: 11px;
}
.transloadit-file-preview-area li:first-child {
border-top: none;
}
Customizing the Progress Bar
If you don't like the Transloadit progress bar, you can render your own, like this:
$('#upload-form').transloadit({
modal: false,
onProgress: function(bytesReceived, bytesExpected) {
// render your own progress bar!
$('#progress')
.text((bytesReceived / bytesExpected * 100).toFixed(2) + '%');
},
onError: function(assembly) {
alert(assembly.error + ': ' + assembly.message);
}
});
If you like the default Transloadit progress bar but just want to change a few colors, customize these css selectors in your own css.
Unbinding the plugin
You can unbind the plugin by calling
$('#upload-form').unbind('submit.transloadit');
How to add your own localization / other language strings
You can add your own language strings like so:
var $el = $('#upload-form');
$el.transloadit({
translations: {
'errors.SERVER_CONNECTION_ERROR' : 'Your internet connection seems to be down. Retrying ...',
'errors.SERVER_CONNECTION_ERROR.retries_exhausted' : 'Your internet connection seems to be down. Once it is up and running again please reload your browser window and try again.',
'errors.ASSEMBLY_NOT_FOUND' : 'There was a server problem finding the proper upload. Please reload your browser window and try again.',
'errors.INTERNET_CONNECTION_ERROR_UPLOAD_IN_PROGRESS' : 'Your internet connection seems to be offline. We will automatically retry the upload until the connection works again. Please leave the browser window open.',
'errors.INTERNET_CONNECTION_ERROR_UPLOAD_NOT_IN_PROGRESS': 'Your internet connection seems to be offline. Please leave the browser window open, so that we can retry fetching the status of your upload.',
'errors.MAX_FILES_EXCEEDED' : 'Please select at most %s files.',
'errors.unknown' : 'There was an unknown error.',
'errors.tryAgain' : 'Please reload your browser page and try again.',
'errors.troubleshootDetails' : 'If you would like our help to troubleshoot this, ' + 'please email us this information:',
'cancel' : 'Cancel',
'cancelling' : 'Cancelling ...',
'details' : 'Details',
'startingUpload' : 'Starting upload ...',
'processingFiles' : 'Upload done, now processing files ...',
'uploadProgress' : '%s / %s MB at %s kB/s | %s left',
}
});
Then just replace the English strings with your custom language strings.
How to access the internal plugin object
You can access the internal uploader object to call methods directly on it like so:
var $el = $('#upload-form');
$el.transloadit({
wait: true
});
var uploader = $el.data('transloadit.uploader');
// then call some methods on the uploader object
uploader.start();
uploader.stop();
// hide the modal if it exists
uploader.hideModal();
// alternatively you could also do it like this
$el.transloadit('start');
$el.transloadit('stop');
Please consult the plugin's source code to see all available methods.
Contributing
Feel free to fork this project. We will happily merge bug fixes or other small improvements. For bigger changes you should probably get in touch with us before you start to avoid not seeing them merged.
Dependencies
This plugin includes the following dependencies:
- jquery.jsonp.js by Julian Aubourg (MIT License)
- toolbox.expose.js by Tero Piirainen (Public domain)
- json2.js by Douglas Crockford (Public domain)
- socket.io by Guillermo Rauch (MIT License)
A big thanks goes to the authors of these fantastic projects!
License
The Transloadit jQuery SDK is licensed under the MIT license. The dependencies have their own licenses (MIT, BSD, PUBLIC DOMAIN).