Thumbr.io Uploader

Getting started

To use the Thumbr.io uploader, you have to import the css and the js library of dropzone.

<link media="all" rel="stylesheet" type="text/css" href="//www.thumbr.io/css/dropzone.css"></link>
<script type="text/javascript" src="//www.thumbr.io/js/thirdparty/dropzone.min.js"></script>
<script type="text/javascript" src="//www.thumbr.io/js/thumbrio.uploader.js"></script>
        

To use our uploader it is necessary to make use of the thumbrio.uploader.js. The next example will use the uploading restrictions specified in Upload Default Settings. Assure you have the option Enable uploads marked. In the next section this piece of code will be detaily explained.

<script type="text/javascript">
    var dropzoneSettings = {addRemoveLinks: true}
    var uploaderSettings = {
        onSuccessUpload: function (URL, file) {alert('The image ' + URL + ' was uploaded successfully');},
        onErrorUpload: function (URL, file) {alert('Error uploading the image ' + URL);},
    }
    var api_key = 'your-api-key';
    var uploaderConstraints = {'maxSize': 2 * 1000 * 1000};  // 2 MB

    var uploader_big = new UploaderThumbrio(document.querySelector('#my-uploader'), dropzoneSettings);
    uploader_big.setUploaderSettings(api_key, uploaderSettings);
    uploader_big.setUploaderOptionsByApiKey(uploaderConstraints);
</script>

Finally, you have to insert your uploader in your html. As our plugin use dropzone, it is very important not to forget to add the class dropzone in our uploader.

<div id="my-uploader" class="dropzone"></div>

If you have follow these steps carefully you will get an uploader like this.

If you are going to use your own amazon bucket it is very important to follow the next steps:

  • Go to your amazon s3 bucket
  • Select the bucket you are going to use, click on Properties and then click on Edit CORS configuration
  • Make sure you have the next tags in the xml file:
         <AllowedMethod>GET</AllowedMethod>
         <AllowedMethod>POST</AllowedMethod>
         <AllowedOrigin>http://my.domain.com</AllowedOrigin> or <AllowedOrigin>*</AllowedOrigin>
         <MaxAgeSeconds>3000</MaxAgeSeconds>
         <AllowedHeader>*</AllowedHeader>

The functions

In this section will be detaily explained all the functions we have employed. Let's start by the constructor

The constructor

The constructor have two arguments: The first one is the HTML Elements or a single HTML Element that will be used as an uploader. The second one is a dictionary with the options to initialize the object Dropzone. To consult all these options visit the official web of dropzone.

Note: You are forced to specificed the option url, but our plugin will initialize it according to your settings. So we recommend to leave this option in blank.

Method setUploaderSettings

This function has two arguments: The first one is the api key of the user. The second one is a dictionary with the options explained in the next table.

Option type Observations
onSuccessUpload function (url, file) This function will be run if the file was uploaded correctly. The first argument is the URL where the image is and the second argument is the file object.
onErrorUpload function (url, file) This function will be run if the file was not uploaded correctly. The first argument is the URL where the image is supposed to be and the second argument is the file object.
filenamePattern str The file name we want. We can use these variables: '$timestamp', '$sequence', '$fileextension', '$filename'. (default: '$filename.$fileextension')

Method setUploaderOptionsByApiKey

Set the uploader options according to your settings by default. This function has only one argument. You are able to define a more restrictive uploader options throught the only argument which has this method. The mentioned options are described in the table below.

Option type Observations
contentTypes List of str We specify the contentTypes of the files.
maxSize int Maximum size of the uploaded file expresed in bytes. The maximum size allowed is 5GB (default: 5 * 1000 * 1000 * 1000 Bytes)
minSize int We specify the minimum number of bytes the file can get.

Note: The path where the objects will be stored has this shape according to your backend:
             thumbrio-s3: /uploads/your-api-key/personal-path/year/month/day/hours_minutes_seconds/random_number/
             amazon-s3 and dropbox: /personal-path/year/month/day/hours_minutes_seconds/random_number/

Using the Uploader ignoring the uploading settings by default

In the last example we have seen how to use the settings by default adding some restrictions extras throught the javascript thumbrio.uploader.js. Now, we want define all the uploading restrictions without having into account the settings by default. Let's have a look to this example:

<script type="text/javascript">
    var dropzoneSettings = {addRemoveLinks: true}
    var uploaderSettings = {
        onSuccessUpload: function (URL, file) {
            alert('The image ' + file.name ' was upload succesfully. Watch it in: ' + URL);},
        onErrorUpload: function (URL, file) {
            alert('The image ' + file.name + ' cannot be uploaded. Message error: ' + file.xhr.responseText);
        },
    }
    var api_key = 'your-api-key';
    var uploaderConstraints = {
        'backend': 'thumbrio-s3',
        'path': 'my-images/',  
        'expirationDate': '2015-09-01T00:00:00Z',
        'contentTypes': ['image/png', 'image/gif'],
        'minSize': 0,
        'maxSize': 5 * 1000 * 1000,
        'acl': 'public-read',
        'publicKey': 'this-is-my-thumbrio-storage-public-key',
        'policy': {'imagen/png': '***', 'imagen/gif': '***'},
        'signature': {'imagen/png': '***', 'imagen/gif': '***'},
    });
    var uploader_big = new UploaderThumbrio(document.querySelector('#my-uploader'), dropzoneSettings);
    uploader_big.setUploaderSettings(api_key, uploaderSettings);
    uploader_big.setUploaderOptions(uploaderConstraints);
</script>

In this example, the uploader will be able to upload images before the 1st of September 2015. These files, that will be uploaded in the folder /my-images/, must be in format png or gif and have less than 5,000,000 Bytes (5MB). We have a different policy and signature by each content type defined. Both of them are generated throught a method that you can see below.

Method to generate policy and signature

import json
import base64
import hashlib
import hmac


THUMBRIO_BUCKET = 'thumbrio'


def generate_policy_and_signature(private_key, key, expiration_date, content_types, min_size,
                                  max_size, backend, acl=None, bucket_name=None):
    """
    Arguments:
        private_key (str): The thumbrio private key if you are using dropbox, amazon private key if
                           you are using s3.
        key (str): The prefix of the filename.
        expiration_date (str): The date when the signature and policy resulted will be deprecated.
        content_types (List[str]): The content types splited in a list.
        min_size (int): The min size of the file.
        max_size (int): The max size of the file.
        backend (str): The backend Three possible options: dropzone, thumbrio-s3 or amazon-s3.
        acl (str): (Only in s3) Two possible options: public-read or private
        bucket_name (str): (Only in amazon-s3) The bucket name of amazon s3.

    Returns:
        (List[]): A list of two elements: Policy and Signature. These two elements is a dictionary
            with the content type as a key.

    Example:
        If we want a policy that allow us to upload png and html files to our thumbrio-s3 backend we
        have to run this command. Let's considerate this restrictions:
            * You will be able to upload files until the 1st September 2015.
            * The files must have a size between 0 and 2MB.
            * The files will be private.
            * The filename must start by the string ''

        policy, signature = generate_policy_and_signature(
            'my-private-key', '', '2015-09-01T00:00:00Z', ['image/png', 'text/html'],
            0, 2 * 1000 * 1000, 'thumbrio-s3', 'private'
        )
    """
    policy = {}
    signature = {}
    for content_type in content_types:
        conditions = [
            ['starts-with', '$key', str(key)],
            ['starts-with', '$Content-Type', str(content_type).replace('*', '')],
            ['content-length-range', min_size, max_size]
        ]

        # The bucket name and the acl do not make sense when the storage backend is 'dropbox'.
        if backend in ('thumbrio-s3', 'amazon-s3'):
            conditions.append({'bucket': str(bucket_name) if backend == 'amazon-s3' else THUMBRIO_BUCKET})
            conditions.append({'acl': str(acl)})

        policy_json = json.dumps({'expiration': str(expiration_date), 'conditions': conditions})
        policy[content_type] = base64.b64encode(policy_json)
        signature[content_type] = base64.b64encode(
            hmac.new(str(private_key), policy[content_type], hashlib.sha1).digest()
        )
    return [policy, signature]

Method setUploaderOptions

This function is only useful if you known how to generate the policy and signature needed to upload something into amazon or dropbox. Belower it is explained how to do it. If you are going to use this function, it is mandatory to use all the options listed in the next table.

Option type Observations
backend str The type of backend. The possible values are: thumbrio-s3, amazon-s3 or dropbox.
path str The path where the files will be uploaded. It must end by '/'. For example: 'one/two/', or '/'.
expirationDate str The expiration date of the policy and the signature. It must be expressed in this format YYYY-MM-DDTHH:MM:SSZ. Example: 2013-01-21T21:30:00Z.
signature Dict <str,str> The signature associated to a contentType to upload a file. Below, it is explained how to create this value.
policy Dict <str,str> The policy associated to a contentType to upload a file. Below, it is explained how to create this value.
bucketName str (Only in amazon-s3) The bucket name.
region str (Only in amazon-s3) The region name. It can be one of these: us-east-1, us-west-2, us-west-1, eu-west-1, eu-central-1, ap-southeast-1, ap-southeast-2, ap-northeast-1, sa-east-1
publicKey str (Only in s3) The amazon s3 access key. Check it out here
acl str (Only in s3) We specify if the file will be public-read or private.
maxSize int (Only in dropbox). Maximum size of the uploaded file expresed in bytes
minSize int (Only in dropbox). Minimum size of the uploaded file expresed in bytes