Giter Club home page Giter Club logo

jquery-sdk's Introduction

Build Status

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 the onUpload 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 CEASED 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="{&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 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:

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!');
    },
  });
});
Parameter Description
onStart(assemblyObj) This is fired whenever uploading begins. The assemblyObj contains useful data like the assembly's id.
onExecuting(assemblyObj) This is fired whenever uploading is fully finished and transcoding begins. The assemblyObj contains useful data like the assembly's id.
onFileSelect(
fileObject,
$fileInputField
)
This is fired whenever a user selects a file in file input field.
onProgress(
bytesReceived, bytesExpected
)
This is fired whenever the upload progress is updated, allowing you to render your own upload progress bar.
onUpload(upload) This is fired once for each uploaded file. This is useful for custom renderings of multiple file uploads.

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.

onResult(step, result) This is fired each time a result becomes available for a given Step, and is only available when wait is set to true. This can be used to show thumbnails for videos or images once they are uploaded.

Results here contain a key original_id, which maps them back to the ID of the originally uploaded file's ID.

onCancel() This is fired after an upload has been canceled by the user.
onError(assembly) This is fired when upload errors occur.
onSuccess(assembly) This is fired when the plugin has completed an upload. If wait is set to false, this is fired after the upload finishes. If wait is true, this is fired once all files have been transcoded.
onDisconnect() This is called whenever the internet connection goes down. Useful in the context of resumable uploads. Transloadit will display a default error message in this case, though, asking the user to keep their browser tab open and wait for the resume.
onReconnect() This is called whenever the internet connection becomes available again after it had been down previously.

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'
  });
});
Parameter Description
service The service URL to use. By default this is "https://api2.transloadit.com/", which makes use of our entire api and route traffic based on the geolocation of your users. Setting this parameter overrules the region parameter, which you should also check out.
region If you want to temporarily switch to a particular region only, because we are down in the other region, you can set this parameter to either "us-east-1" or "eu-west-1". The SDK will then build the proper service endpoint for you. Make sure to not set a custom service endpoint yourself in this case, as this would overrule the region parameter.
wait Specifies whether the plugin should wait for files to be transcoded before submitting the form. This is false by default.
requireUploadMetaData Specifies whether the plugin should wait for meta data of uploaded files to first be extracted before it calls the onSuccess callback. If you set wait to true, this option does not have any effect, because extracting meta of uploaded files is a prerequisite for the files to be transcoded.

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.

params

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:


 $('#upload-form').transloadit({
   wait   : true,
   params : {
     auth  : { key : 'YOUR_TRANSLOADIT_KEY' },
     steps : {
       resize_to_75: {
         robot  : '/image/resize',
         use    : ':original',
         width  : 75,
         height : 75
       },
       // more Steps here
     }
   }
 });
 
signature Specifies the signature string, which is required if signature authentication is enabled in your account. This is null by default. The old way of providing this in a hidden input field named signature is still valid and will not be deprecated.

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!

modal Specifies whether to render the Transloadit overlay and progress bar automatically. This is true by default.
autoSubmit Specifies whether to submit the original form automatically once the upload and processing have completed. This is true by default.
processZeroFiles Specifies whether to perform processing when the form is submitted with no files selected using the form inputs. This is true by default.
triggerUploadOnFileSelection When set to true this triggers the upload to Transloadit as soon as the user has selected a file in any of the form's file input fields. This is false by default.
maxNumberOfUploadedFiles When set to an integer value, this is the maximum number of files users can upload. If they exceed this number, then an error will occur. By default this is null, which means no limit.
locale The locale to use. The default value is "en". If you use a custom locale, please provide your own localized strings. Please check the bottom of this page for further instructions.
exclude Specifies a selector for which any matching input[type=file] elements in the current form will not be uploaded through Transloadit. This is "" by default.
fields

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:


 $('form').transloadit({
   // send no form fields; this is the default
   fields: false
 });
 

If you would like to only send some fields, set this parameter to a CSS selector string matching the fields to be sent:


 $('form').transloadit({
   // only send the fields named "field1" & "field2"
   fields: 'input[name=field1], input[name=field2]'
 });
 

If you would like to send all form fields, set this to true:


 $('form').transloadit({
   fields: true
 });
 

You can also set this to an object of key/value pairs:


 $('form').transloadit({
   fields: {
     name : 'John Doe',
     age  : 26
   }
 });
 

The fields that you send here will be available as ${fields.*} variables in your Assembly instructions. Learn more about that here.

translations An object of i18n translation strings. Please check below to get the list of all available strings to translate.
debug Specifies whether Transloadit errors are displayed to end users. If this is set to false, no Transloadit errors will be displayed. Use the onError callback to perform your own logging or presentation. This is true by default.

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:

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).

jquery-sdk's People

Contributors

acconut avatar avokhmin avatar chrisforrette avatar dependabot[bot] avatar dhennen avatar djanowski avatar felixge avatar greenkeeperio-bot avatar ianjosephwilson avatar ibroadfo avatar ifedapoolarewaju avatar kvz avatar louim avatar nqst avatar rveitch avatar tim-kos avatar tus-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-sdk's Issues

this.$ is not a function

The error is coming from the FilePreview constructor. I believe the issue is simply that $ is not being passed to the constructor but is expected there.

I added PR #64 to fix this.

Document title set to null when complete

Noticed that my document's title was being set to null after uploading a file.

The Uploader's documentTitle attribute is initialized to null on line 72

Then, documentTitle is set to document.title, but only for Firefox

Then, in various places, document.title is reassigned to the uploader.documentTitle.

Am I missing something here? I don't see this.documentTitle get assigned anywhere else.. just NULL, or the current value if you're in firefox.
This can't be the intended behavior..

I'm using this workaround for now:

$element.transloadit({...});
var uploader = $el.data('transloadit.uploader');
uploader.documentTitle = document.title;

Uploader.start() should gracefully handle when files are null

Currently, line 318 expects this.$files to be a jquery object, and results in an undefined function error if it's not. This code should fail gracefully if this.$files is null.

This is the code:

    this.$files.each(function() {
      var $clone = $(this).clone(true);
      self.$fileClones = self.$fileClones.add($clone);
      $clone.insertAfter(this);
    });

jQuery 1.9 support

I'm getting errors about the use of the deprecated browser API in jQuery 1.9:

Uncaught TypeError: Cannot read property 'msie' of undefined
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8

BORED_INSTANCE_ERROR

Hi For more than once, i'm getting upload errors. Seems that there's a cache problem with some json transload webservice using your JQuery SDK

XMLHttpRequest cannot load https://s3.amazonaws.com/infra-us-east-1.transloadit.com/cached_instances.json. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'https://ec-ember-staging.herokuapp.com' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.
{ 
  error: "BORED_INSTANCE_ERROR", 
  message: "Could not find a bored instance. Could not query S3 for cached uploaders from url: https://s3.amazonaws.com/infra-us-east-1.transloadit.com/cached_instances.json"
}

This happens when uploader tries a GET from http://infra-us-east-1.transloadit.com.s3.amazonaws.com/cached_instances.json and aborts.

I think is because i'm using an ajaxPrefilter but not sure:

Ember.$.ajaxPrefilter(function (options) {
  options.crossDomain = {
    crossDomain: true
  };
  options.xhrFields = {
    withCredentials: true
  };
});

if that's not the problem why is this happening? and/or how can i solved it? it used to work until now

BTW: it works sometimes and sometimes it isn't

thanks

destroy/detach method

Hi guys,

I ran into a situation where I needed to attach/detach transloadit plugin dynamically.
Currently I resolved this issue simply unbinding it with

$("formSelector").unbind("submit.transloadit");

but a method exposed would be better and easier to use.

Uploading only 1 file field at a time

My form contains several image upload fields, and I would like to display thumbnails as soon as they are selected. That's why I am listening for the user's selection to trigger an upload:

fileInput.change(function(){
  // Trigger the file upload: How do I trigger that only the file from my current input field is uploaded?
  $(this).closest("form").trigger("submit.transloadit"); 
});

As you can see in the example, I am triggering the upload of all fields. Is there the possibility to limit upload to a specific field? I thought about setting the "exclude" option before the trigger, or moving the other file inputs out of the form temporary. Perhaps there is a nicer solution?

Original file input being removed with clones

Not sure if this is intended behavior โ€“

I have a simple form where users can upload a profile photo. It has one file input, but it is part of a multi-step set up process so I don't want the page refreshing. The photo selects and uploads fine, but I believe my original input field is being lumped in with the "clones" when they get removed from the DOM.

Ideally I'd like to retain the original input with its event intact so that a user can select a different photo after uploading one. It seems that currently the input and associated events are destroyed upon submit.

Plugin options:
wait: true
onResult: simple handler to insert image in to DOM

Progress event may return 0 as number of bytes expected in IE8

I've been running into troubles using the lib on IE8. As far as I can tell, the JSONP "success" callback may be called with an assembly object that has bytes_expected set to 0. When renderProgress is called, a division by zero occurs at line 515 and the progress variable becomes NaN. In turn, this makes jQuery crash on the call to animate at line 523.

Wrapping the division in an if loop that sets progress to 0 when bytes_expected is 0 solved the problem for me.

debug option has no effect

There is no reference to the debug option in the library. In particular, the documentation says that setting debug to false will prevent error modals. I'd like to retain the upload progress indicator, but turn off the error modal. It doesn't seem that this is possible, currently. Should I submit a PR?

Unexpected token ':'

If I import uppy.min.js.map into my page, console return me:
Uncaught SyntaxError: Unexpected token ':' (at line n.2)

Thanks

maxNumberOfUploadedFiles - Error still returned on subsequent upload attempts even within allowable limits.

Hello!

I'm using maxNumberOfUploadedFiles to restrict the number of uploads.

If I attempt to upload more than the specified max number of uploads, I get the MAX_FILES_EXCEEDED error returned as you would expect. So far, so good.

However, if I then attempt to upload a number of files within the max allowable - even just a single file - I still get the MAX_FILES_EXCEEDED error returned.

It's as though Transloadit still has in memory the files from the previous attempt.

This is the code I'm using...

$('#vehicle-images-form').transloadit({
    wait: true,
    autoSubmit: false,
    triggerUploadOnFileSelection: true,
    processZeroFiles: false,
    maxNumberOfUploadedFiles: 2,
    params: {
      auth: { key: "xxx" },
      template_id: "xxx"
    },                    
    onError: function(assembly) {
        console.log(assembly);
        // handle error
    },            
    onSuccess: function(assembly) {
        console.log(assembly);
        // do something
    }
});

v3: Drag&Drop onFileSelect callback behaves in an undocumented way.

HI!
The documentation says the the first argument of the onFileSelect callback will be the filename, but when it's called after dropping a file into a Drag&Drop area, the first argument is an Object of file metadata, including the name.

I don't know which way is the intended way going forward, but I figured they should be consistent.

clone input when using formData

I clone the repo https://github.com/tim-kos/transloadit-drag-and-drop, and it works fine. While I update jquery.transloadit to the latest version, the issue that clone the input after dropping an image occurs.

Reproduce steps:

  1. clone https://github.com/tim-kos/transloadit-drag-and-drop
  2. edit index.html
  3. replace <script src="lib/transloadit.js"></script> with <script src="https://assets.transloadit.com/js/jquery.transloadit2-v2-latest.js"></script>
  4. open index.html in browser.
  5. drag and drop an image.
  6. there will be 2 inputs. if you drop again, there will be 4 inputs, if you drop again, there will be 8 inputs........

8inputs

TEXTAREA gets prepended into FORM

When I use the plugin and I get a successful assembly, a TEXTAREA gets prepended into the FORM.

If I use the FORM in an async environment, and never reload the page where it is, the second assembly built (and every other) with that form will have that TEXTAREA there.

Then, in the plugin, if fields: true or fields: '*', the POST will send that input fields polluting the next assemblies.

What is the use case for that input field being there?ยฟ

Submit form when no file is selected.

I was having some issues when user submits form and no file is selected. I believed that processZeroFiles option takes cares of this, but I think it doesn't.

Looking at init() function:

Uploader.prototype.init = function($form, options) {
    this.$form = $form;
    this.options($.extend({}, OPTIONS, options || {}));

    var self = this;
    $form.bind('submit.transloadit', function() {
      self.validate();
      self.detectFileInputs();
      if (!self._options['processZeroFiles'] && self.$files.length === 0) {
        self.submitForm();
      } else {
        self.getBoredInstance();
      }

      return false;
    });

    this.includeCss();
  };

Checks if processZeroFiles is !false and no file is selected, so if it's true it submits the form anyway.

Then I look submitForm() function:

 Uploader.prototype.submitForm = function() {
    if (this.$fileClones) {
      this.$fileClones.remove();
    }

    if (this.assembly !== null) {
      $('<textarea/>')
        .attr('name', 'transloadit')
        .text(JSON.stringify(this.assembly))
        .prependTo(this.$form)
        .hide();
    }

    this.$form
      .unbind('submit.transloadit')
      .submit();
  };

And after all the checks, it unbinds submit.transloadit and submits to the form action setted, in my case, and written in docs, api2.transloadit.com/assemblies so I am redirected to that url seeing something like this:

cap tloadit

Hope this will be useful.

!important in transloadit2.css

Is there any particular reason to use !important throughout the CSS? It makes it a little harder to customize, since the CSS gets loaded dynamically via jscript after page load, and clobbers any existing CSS I have. Your !important also over-rides any !important that I add, since it's loaded later. Got it working by prefixing all my CSS rules with 'body' to increase specificity, but would be easier to avoid it if there's no particular reason to use !important (?).

A failed assembly triggers a file upload to our servers

With the following configuration, if TransloadIt returns a AUTH_EXPIRED response or some other code, then the error dialog reflects that, but in the background, it still goes ahead and uploads the file (Chrome shows "Uploading (5%)" in the bottom left corner).

wait: true
processZeroFiles: false

If TransloadIt sends back an error code, it should abort the upload completely to prevent bandwidth on our and your end.

What I think needs to happen:

  • The XMLHTTPRequest object needs to be stored as $request (or other variable( on the upload object for reference later
  • In the event of either Uploader.prototype.stop or Uploader.prototype.cancel being called, then you need to call $request.abort() to stop the upload

Also, in this event, the transloadit form field shouldn't be filled in, and the form shouldn't be autosubmitted. At the moment, if people cancel, then hit the submit button again, it submits the form with an empty file field and a filled in transloadit form field.

V3: this._modal.renderCancelling() is still invoked when modal is set to false.

We've encountered a breaking issue in v3 of the SDK that occurs when cancelling an upload if the modal parameter is set to false for custom progress rendering. An error will be thrown by this._modal.renderCancelling() as it is not wrapped in a conditional to prevent it from being invoked when modal is false, and the modal object will then be undefined.

I've submitted PR #53 to resolve the issue, but until it is merged we'll need to continue using a forked custom build of the SDK with this hotfix included.

Thanks in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.