Announcement

Collapse
No announcement yet.

Valence.util.Helper.download()

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Valence.util.Helper.download()

    Is there a way to wrap this so that I can use Ext.getBody().mask() so that the user knows the job is running and prohibits further input until it's finished?

    I've yet to figure out a way to do this other than making an Ajax call that runs the job and places the output on the IFS and then in the Ajax success function use the Helper.download() to go get it.

  • #2
    Valence.util.Helper.download does not have any mechanism to let you know when it is completed so your suggested approach is correct.

    Comment


    • #3
      You could create your own method to download a file and have a callback called after the process is completed.

      Example downloadFile Method:
      Code:
      /**
       * download example with "XMLHttpRequest"
       * @param{Object} config
       *
       *  config:
       *  - `callback` [optional] Callback after process is finished passes one param boolean success true/false
       *  - `timeout`  [optional] Override the base timeout
       *  - `url`      URL
       */
      var downloadFile = function (config) {
          var oReq = new XMLHttpRequest(),
              errorTitle = 'Error',
              errorButtonText = 'OK',
              processCallback = function (success) {
                  if (!Valence.isEmpty(config.callback) && typeof config.callback === 'function') {
                      config.callback(success);
                  }
              };
      
      
          // setup request
          //
          oReq.open('GET', config.url, true);
      
      
          // check to see if we need to adjust the timeout
          //
          if (!Valence.isEmpty(config.timeout)) {
              oReq.timeout = config.timeout;
          }
      
      
          oReq.responseType = 'arraybuffer';
      
      
      /**
           * timed out
           */
      oReq.ontimeout = function () {
              processCallback(false);
      Valence.util.Helper.showDialog(errorTitle, 'Request Timed Out', errorButtonText);
          };
      
      
      /**
           * load of the request
           */
      oReq.onload = function () {
              // If the response isn't JSON then attempt to download
              //
              if (oReq.getResponseHeader('Content-Type').indexOf('application/json') === -1) {
      /**
                   * Notify user the browser isn't supported
                   */
      var showUnsupportedBrowser = function () {
      
      Valence.util.Helper.showDialog(errorTitle, 'Unsupported Browser', errorButtonText);
                  };
      
                  if ('Blob' in window) {
                      var disposition = oReq.getResponseHeader('content-disposition'),
                          contentType = oReq.getResponseHeader('Content-Type') || '',
                          blob = new Blob([oReq.response], {type: contentType}),
                          fileName = '';
      
                      // get the file name
                      //
                      if (!Valence.isEmpty(disposition)) {
                          var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/,
                              matches = filenameRegex.exec(disposition);
                          if (matches != null && matches[1]) {
                              fileName = matches[1].replace(/['"]/g, '');
                          }
                      }
      
      
                      if (!Valence.isEmpty(fileName)) {
                          var URL, downloadUrl;
      
      
                          // Downloading the file depends on the browser
                          //
                          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, fileName);
                          } else {
                              // create a download anchor tag
                              //
                              var downloadLink = document.createElement('a');
      
                              downloadLink.target = '_blank';
                              downloadLink.download = fileName;
      
      
                              // create an object URL from the Blob
                              //
                              URL = window.URL || window.webkitURL;
                              downloadUrl = URL.createObjectURL(blob);
      
      
                              // set object URL as the anchor's href
                              //
                              downloadLink.href = downloadUrl;
      
      
                              // append the anchor to document body
                              //
      document.body.append(downloadLink);
      
      
                              // fire a click event on the anchor
                              //
                              downloadLink.click();
      
                              // cleanup: remove element and revoke object URL
                              //
      document.body.removeChild(downloadLink);
                              URL.revokeObjectURL(downloadUrl);
                          }
      
                          processCallback(true);
                      } else {
                          //error file name not supplied and it's required
                          //
                          processCallback(false);
      
      Valence.util.Helper.showDialog(errorTitle, 'Invalid File Name', errorButtonText);
                      }
                  } else {
                      processCallback(false);
      
                      //unsupported browser
                      //
                      showUnsupportedBrowser();
                  }
              } else {
                  // Since it's JSON we must have encountered an error since we are requesting a download
                  // assume if JSON response it responds with param `msg` "Erorr Message"
                  if (!Valence.isEmpty(Uint8Array) && typeof Uint8Array === 'function') {
                      var d;
      
                      // convert the binary JSON response back to a JSON object
                      //
                      oReq.responseText = decodeURIComponent(escape(new Uint8Array(oReq.response).reduce(function (data, _byte) {
                          return data + String.fromCharCode(_byte);
                      }, '')));
      
                      d = JSON.parse(oReq.responseText);
      
                      processCallback(false);
      
                      // alert the user of the error
                      //
                      if (Valence.isEmpty(d) || Valence.isEmpty(d.msg)) {
                          d.msg = 'Error creating file';
                      }
      
                      Valence.util.Helper.showDialog(errorTitle, d.msg, errorButtonText);
                  }
              }
          };
      
      
      /**
           * make the request
           */
      oReq.send(null);
      };
      Example calling the downloadFile method:
      Code:
      downloadFile({
          url: '/valence/vvcall.pgm?pgm=EXGRIDALL&action=downloadPDF',
          timeout: 300000,  // override browser default timeout to 5 minutes "milliseconds"
          callback: function(success) {
              if (success) {
                  console.log('Downloaded File');
              } else {
                  console.log('Did Not Download File');
              }
          }
      });

      Comment


      • #4
        That's some beyond advanced technique stuff there Johnny. Needless to say you've done it before! Thanks!

        Comment

        Working...
        X