CoT Dropzone

CotDropzone Class

A wrapper class implementing the 3rd party DropzoneJS object.

Constructor

var cdz = new CotDropzone();
Creates a new CotDropzone object.

Property(ies)

dropzone

var dz = cdz.dropzone;

Dropzone object type. After the render method is called, the new Dropzone object is assigned to the dropzone property.

Method(s)

render(options)

var options = {
    url: 'http://maserati.corp.toronto.ca:9097/c3api_upload/upload/apptest/ref'
};

cdz.render(options);

Accepts an object type options argument. The options argument contains properties as defined by DropzoneJS.

The class property defaultOptions is used to fill in missing properties. When a preset is defined (which is defined as "default" in defaultOptions), the preset will also fill in the missing properties.

addFile(file)

var file = { name: 'file.txt', size: 1000, type: 'text/plain' }

var cdz = new CotDropzone();
cdz.render(...);
cdz.addFile(file);

Accepts a Dropzone File type file argument. Calls the current the preset's addFile function property. This is used to add a file correctly into the dropzone object.

addFiles(...files)

var file1 = { name: 'file1.txt', size: 1000, type: 'text/plain' }
var file2 = { name: 'file2.txt', size: 1000, type: 'text/plain' }

var cdz = new CotDropzone();
cdz.render(...);
cdz.addFiles(file1, file2);

Accepts one or more Dropzone File type file argument. Calls the current the preset's addFiles function property. This is used to add multiple files correctly into the dropzone object.

addInitialFile(file)

var file = { name: 'file.txt', size: 1000, type: 'text/plain' }

var cdz = new CotDropzone();
cdz.render(...);
cdz.addInitialFile(file);

Accepts a Dropzone File type file argument. Calls the current the preset's addInitialFile function property. This is used to add an initial file correctly into the dropzone object.

addInitialFiles(...files)

var file1 = { name: 'file1.txt', size: 1000, type: 'text/plain' }
var file2 = { name: 'file2.txt', size: 1000, type: 'text/plain' }

var cdz = new CotDropzone();
cdz.render(...);
cdz.addInitialFiles(file1, file2);

Accepts one or more Dropzone File type file argument. Calls the current the preset's addInitialFiles function property. This is used to add multiple initial files correctly into the dropzone object.

Static Property(ies)

defaultOptions

Object type. Defines the initial option for all new CotDropzone object used by the render method.

Static Method(s)

mergeFunctions(...funcs)

var oldFunction = function() { ... };
var ignore = null;
var newFunction = function() { ... }

oldFunction = CotDropzone.mergeFunctions(oldFunction, ignore, newFunction);

Accepts one or more function type arguments. Function type return value. A helper function used to combine one or more functions into a single function.

When the new function is called, all the argument functions are called in the order they are passed in. Non-function arguments are not called.

This can be used to override existing function without loosing the original function.

Presets

Present are pre-defined dropzone options and custom implementations. Some properties are intended to be overwritten for custom implementation.

Common Preset

Provides common implementations for common dropzone options.

init()

Function type. Dropzone initialiation function. Common preset implementation contains accessibility hooks.

announce(message)

CotDropzone.presets.common.announce('Message to announce');

Function type. Accepts a string type message argument. Announces the message to screen reader.

addFile(file)

Function type. Accepts a Dropzone file type file argument.

addFiles(...files)

Function type. Accepts one or more Dropzone file type file arguments.

addInitialFile(file)

Function type. Accepts a Dropzone file type file argument.

addInitialFiles(...files)

Function type. Accepts one or more Dropzone file type file arguments.

thumbnailDataUris

var wordDocThumbnail = CotDropzone.presets.common.thumbnailDataUris['application']['msword'];

Nested object type. Defines default thumbnail images for common mime types as svg datauris.

Default Preset

Dropzone options used by CotDropzone by default. Some options refers to the common presets options. Any default preset options can be over written by user provided options.

autoQueue

Boolean type. Set to the value of false. Part of DropzoneJS options.

thumbnailHeight

Number type. Set to the value of 48. Part of DropzoneJS options.

thumbnailWidth

Number type. Set to the value of 48. Part of DropzoneJS options.

previewTemplate

String type. Defines the HTML string used for rendering newly added files. Part of DropzoneJS options.

init()

Function type. A merge of CotDropzone.presets.common.init function and a custom function. Custom function adds the description and the top and bottom buttons, attach dropzone event handlers and update the UI on changes. Part of DropzoneJS options.

announce(message)

Function type. The same as CotDropzone.presets.common.announce.

thumbnailDataUris

Nested object type. The same as CotDropzone.presets.common.thumbnailDataUris.

fields

var options = {
    fields: [{
        name: 'field1',
        title: 'Field One',
        prehelptext: 'Pre help text',
        posthelptext: 'Post help text',
        type: 'text',
        required: true,
        validators: {
            regexp: {
                regexp: /^[^<>']*$/
                message: 'Must not contain invalid characters'
            }
        }
    }],

    preset: 'default'
}

var cdz = new CotDropzone();
cdz.render(options);

Array of object type. Set to an empty array. Should be overwritten. Used to configure the fields that will be added to the previewTemplate. Field values will be stored on to the associated Dropsone file object inside the fields property.

The field object can contain the following properties

  • name - String type. The field's name and is used to determine the field's id attribute.
  • id - String type. Same as name.
  • title - String type. The field's label.
  • prehelptext - String type. Help text that appears below the label and above the form field.
  • posthelptext - String type. Help text that appears below the label and below the form field.
  • type - String type. The field type. Valid values are 'text' and 'textarea'
  • required - Boolean type. Uses CotForm's required validation. Only implemented when CotDropzone is used inside a CotForm.
  • validators - Object type. FormValidation.io's validators. Only implemented when CotDropzone is used inside a CotForm.

onFieldChange(file, files)

var cdz = new CotDropzone();
var options = {
    fields: [{ name: 'field1', title: 'Field One', type: 'text' }],

    onFieldChange: function(file, files) {
        console.log('FIELD CHANGED')
    },

    preset: 'default'
};
cdz.render(options);

Function type. Should be overwritten. Is called after the field element triggers the change event and the value is stored inside the dropzone file object.

getFieldsTemplate()

Function type. Returns string type value.

setFieldsTemplate(file, row)

Function type.

getSid()

Function type.

getNasLink(file)

Function type.

getLink(file)

Function type.

setLink(file)

Function type.

addFile(file)

Function type.

addFiles(...files)

Function type.

addInitialFile(file)

Function type.

addInitialFiles(...files)

Function type.

valueMapFromFiles(file)

Function type.

valueMapToFiles(data)

Function type. Takes an object type.

Dropzone Field in Cot Form

var model = new CotModel();

var definition = {
    useBinding: true,

    success: function(event) {
        event.preventDefault();
        alert('SUCCESS');
        return false;
    },

    sections: [{
        rows: [{
            fields: [{
                options: {
                    fields: [{
                        title: 'Text Input',
                        name: 'field01',
                        type: 'text',
                        required: true
                    }, {
                        title: 'Text Input',
                        name: 'field02',
                        type: 'textarea'
                    }],

                    maxFilesize: 10,
                    maxFiles: 20,

                    preset: 'default',

                    url: 'http://maserati.corp.toronto.ca:9097/c3api_upload/upload/apptest/ref',
                },

                id: 'dz',
                bindTo: 'dz',

                title: 'test',
                posthelptext: 'post help text',
                prehelptext: 'pre help text',
                
                type: 'dropzone',
                ignoreUploadError: true,
                allowFormsubmitionWithUploadError: true
            }]
        }]
    }]
};

var cotForm = new CotForm(formDefinition);
cotForm.setModel(model);
cotForm.render({ target: '#targetElement' });

New Properties Added In CoreJs 9.4.0

Changes to Dropzone

In addition to the above change we added new options to the Dropzone:
An example from the Burial Permits app, here is a CoT Form Dropzone field:

The new field values are:
useJSONcustomMeta
This means the custom-meta header will be sent as a header and if you turned on “use_recaptcha” then the “captcha” key will be added into to that JSON object.

There new new options key that goes along with the above property:
getHeadersAsJson
This allows you to specify what the JSON in your custom-meta object should be. Note in side the custom-meta we will overwrite the “captcha” key if it is in your object. To send a captcha token just turn use_recaptcha on.

Note: If you are using the above options in most cases you will be implementing a SSJS on Upload API to process the request. The detail for that are not covered here.

Example use case for useJSONcustomMeta:

Using it to send a JWT token for a upload file event with a Captcha token.

  {
    fields: [
      {
        id: 'statementOfDeath',
        title: 'Statement of Death/Stillbirth and Supporting Forms',
        bindTo: 'statementOfDeath',
        prehelptext: 'Please upload the completed Statement of Death/Stillbirth form and all supporting forms.',
        type: 'dropzone',
        required: true,
        useJSONcustomMeta: true,
        use_recaptcha: true,
        recaptcha_sitekey: '/* @echo RECAPTCHA_SITEKEY */',
        options: {
          getHeadersAsJson: function() {
            return {
              "idToken": burialPermitApp.getCurrentIdToken()
            }
          },
          retrieveAsFileDownload: true,
          addFileButtonName: 'Upload Forms',
          timeout: 0,
          acceptedFiles: 'application/pdf,.pdf,pdf,*.pdf',//"pdf/*,application/pdf,application/PDF",
          maxFiles: 1,
          maxFilesize: 5,
          url: '/*@echo ROOT_ENV_DA *//*@echo UPLOAD_URL */'+"bc_"+isBusinessCode+"_bc"
        }
      }
    ]
  }


There are few more options added:
retrieveAsFileDownload
downloadButtonClasses

Turning retrieveAsFileDownload option on means you will be handling the file download instead of the default which is an HTTP GET request to get the file (note we added target=”_blank” to the URL too in this release) . Turning this option on will change the link (element) into a button (element). This button will have a class as defined in the property downloadButtonClasses or the default value: `js-dropzoneHandleFileDownload`.
You can then choose to handle what should happen when that button is clicked by default we don’t add any type of event handling for this button click you will have to add it. This should give developers most flexibility.

I have provided some examples below of how this is used in the burial_permits app. This change is mainly for the VA finding that we are allowed to get files by sending the SID in the URL.

Use case 1: If you don’t want to make a download request:

  'click .js-dropzoneHandleFileDownload': function(event) {
    event.preventDefault();
    $(event.currentTarget).attr("disabled", true);
    let nameOfFile = $(event.currentTarget).data("dz_name");
    CotApp.showModal({
        preset:'alert',
        title: 'Unauthorized',
        body: `<p>The file ${nameOfFile} was uploaded to the server. You are not authorized to download this file.</p>`,
        modalSize: 'modal-md',
        originatingElement: $(event.currentTarget)
    });
    $(event.currentTarget).attr("disabled", false);
    return false;
  }


Use case 2: You want to allow for file download the file and want to send some authentication information along like the SID. To avoid browser saving authentication information in the URL history we want to send that information in the header or the body of the request.

$("#maincontent").off('click', '.js-dropzoneHandleFileDownload').on('click', '.js-dropzoneHandleFileDownload', function(event) {
    event.preventDefault();
    $(event.currentTarget).attr("disabled", true);
    let linkToFile = config.httpHost.app[httpHost] + $(event.currentTarget).data("dz_filelink");
    let nameOfFile = $(event.currentTarget).data("dz_name");
  
    var myHeaders = new Headers();
    myHeaders.append("Authorization", Cookies.get(config.default_repo + ".sid"));
    myHeaders.append("Cache-Control", "no-store");
    var requestOptions = {
      method: 'GET',
      headers: myHeaders
    };
    fetch(linkToFile, requestOptions)
    .then(response => {
      if (response.status === 200) {
        return response.blob();
      } else  {
        throw({"error": response, "status": response.status});
      }
    })
    .then(blob => {
      var url = window.URL.createObjectURL(blob);
      var a = document.createElement('a');
      a.href = url;
      a.download = nameOfFile;
      document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
      a.click();    
      a.remove();  //afterwards we remove the element again  
      $(event.currentTarget).attr("disabled", false);
    })
    .catch(error => {
      console.log('file download error', error);
      if (error.status === 401) {
        cot_app.showModal({
            preset:'alert',
            title: 'Unauthorized',
            body: `<p>You are not authorized to download this file. Please re-login and try again.</p>`,
            modalSize: 'modal-md',
            originatingElement: $(event.currentTarget)
        });
      } else {
        cot_app.showModal({
          preset:'alert',
          title: 'System Error',
          body: `<p>There was an error processing your file download request. Please re-login and try again. If the issue continues please report this problem.</p>`,
          modalSize: 'modal-md',
          originatingElement: $(event.currentTarget)
        });
      }
      $(event.currentTarget).attr("disabled", false);
    });
  });