Apache2-UploadProgress

 view release on metacpan or  search on metacpan

extra/progress.js  view on Meta::CPAN


var progress;

function startPopupProgressBar(form, options) {
    var id = generateProgressID();
    if (form.action.match(/\?/))
        form.action += '&progress_id=' + id;
    else
        form.action += '?progress_id=' + id;

    var width  = options.width  || '480';
    var height = options.height || '150';
    window.open ('/UpdateProgress?progress_id='+id,'Apache2-UploadProgress','location=0,status=0,width='+width+',height='+height); return true;
}

function startEmbeddedProgressBar(form) {
    progress = {};
    progress.id         = generateProgressID();
    if (form.action.match(/\?/))
        form.action += '&progress_id=' + progress.id;
    else
        form.action += '?progress_id=' + progress.id;
    progress.starttime  = new Date();
    progress.lasttime   = new Date(progress.starttime);
    progress.lastamount = 0;
    window.setTimeout( reportUploadProgress, 100 );
    return true;
}

function updateHTMLProgressBar(progress) {
    if (progress.size > progress.received)
        window.setTimeout( function() { window.location.reload() }, 1000 );
    updateProgressBar( progress );
    return true;
}

function updateProgressBar(progress) {

    if (progress.received == progress.size)
        progress.finished = 1;

    // Only calculate rates and times is we were given a starttime
    if (progress.starttime) {
        var currenttime = new Date();
        var totalelapsedtime = ( currenttime.getTime() - progress.starttime.getTime() ) / 1000;
        var lastelapsedtime  = ( currenttime.getTime() - progress.lasttime.getTime() ) / 1000;

        progress.elapsedtime = totalelapsedtime;

        if (totalelapsedtime != 0)
            progress.rate = parseInt( progress.received / totalelapsedtime );
        else
            progress.rate = 0;

        if (lastelapsedtime != 0)
            progress.currentrate = parseInt( (progress.received - progress.lastamount) / lastelapsedtime );
        else
            progress.currentrate = 0

        if (progress.currentrate != 0)
            progress.remainingtime = parseInt( (progress.size - progress.received) / progress.rate );
        else
            progress.remainingtime = '';

        progress.currentrate   = formatBytes(progress.currentrate);
        progress.rate          = formatBytes(progress.rate);
        progress.elapsedtime   = formatTime(progress.elapsedtime);
        progress.remainingtime = formatTime(progress.remainingtime);
    }

    if (progress.size != 0)
        progress.percent = Math.round(progress.received / progress.size * 100);

    progress.size     = formatBytes(progress.size);
    progress.received = formatBytes(progress.received);

    document.getElementById('progress').innerHTML = Jemplate.process('progress.jmpl', progress);
}

function reportUploadProgress() {
    
    url = '/UpdateProgress?progress_id=' + progress.id;

    var req = new XMLHttpRequest();
    req.open('GET', url, Boolean(handleUploadProgressResults));
    // We have to set the qvalue to 1.1 because Konqueror sends
    // it's standard Accept header with our header tacked on the end
    // which means that text/html gets picked first
    req.setRequestHeader(
        'Accept', 
        'text/x-json; q=1.1'
    );
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200)
            handleUploadProgressResults(req.responseText);
    };
    req.send(null);
}

function handleUploadProgressResults(results) {

    var state = JSON.parse(results);

    if ( state != undefined ) {

        state.starttime       = progress.starttime;
        state.lasttime        = progress.lasttime;
        state.lastamount      = progress.lastamount;

        progress.lasttime     = new Date();
        progress.lastamount   = state.received;
        progress.size         = state.size;
        progress.received     = state.received;

        if ( progress.received != progress.size ) {
            window.setTimeout( reportUploadProgress, 1000 );
        }

        updateProgressBar(state);
    }
}

function formatTime(time) {
    var seconds = Math.round(time);
    var minutes = 0;
    if (time >= 60) {
        minutes = Math.round(seconds / 60);
        seconds %= 60;
    }
    if (seconds < 10)
        seconds = '0' + seconds;

    return minutes + ':' + seconds;
}

function formatBytes(bytes, precision) {
    if ( typeof(precision) != 'number')
        precision = 2;
    var suffix = '';

    // Only positive values are allowed
    if (bytes <= 0)
        return bytes;

    if (bytes > 1073741824) {
        bytes /= 1073741824;
        suffix = 'G';
    } else if (bytes > 1048576) {
        bytes /= 1048576;
        suffix = 'M';
    } else if (bytes > 1024) {
        bytes /= 1024;
        suffix = 'K';
    }

    return formatNumber(bytes, precision) + suffix;
}

function formatNumber(number, precision) {
    if ( typeof(precision) != 'number')
        precision = 2;
    var num = new Number(number);
    return num.toFixed(precision)
}

function setActiveStyleSheet(title) {
    var i, a, main;
    for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
        if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
            a.disabled = true;
            if(a.getAttribute("title") == title)
                 a.disabled = false;
        }
    }
}

extra/progress.js  view on Meta::CPAN

*/

// IE support
if (window.ActiveXObject && !window.XMLHttpRequest) {
  window.XMLHttpRequest = function() {
    return new ActiveXObject((navigator.userAgent.toLowerCase().indexOf('msie 5') != -1) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP');
  };
}

// Opera support
if (window.opera && !window.XMLHttpRequest) {
  window.XMLHttpRequest = function() {
    this.readyState = 0; // 0=uninitialized,1=loading,2=loaded,3=interactive,4=complete
    this.status = 0; // HTTP status codes
    this.statusText = '';
    this._headers = [];
    this._aborted = false;
    this._async = true;
    this.abort = function() {
      this._aborted = true;
    };
    this.getAllResponseHeaders = function() {
      return this.getAllResponseHeader('*');
    };
    this.getAllResponseHeader = function(header) {
      var ret = '';
      for (var i = 0; i < this._headers.length; i++) {
        if (header == '*' || this._headers[i].h == header) {
          ret += this._headers[i].h + ': ' + this._headers[i].v + '\n';
        }
      }
      return ret;
    };
    this.setRequestHeader = function(header, value) {
      this._headers[this._headers.length] = {h:header, v:value};
    };
    this.open = function(method, url, async, user, password) {
      this.method = method;
      this.url = url;
      this._async = true;
      this._aborted = false;
      if (arguments.length >= 3) {
        this._async = async;
      }
      if (arguments.length > 3) {
        // user/password support requires a custom Authenticator class
        opera.postError('XMLHttpRequest.open() - user/password not supported');
      }
      this._headers = [];
      this.readyState = 1;
      if (this.onreadystatechange) {
        this.onreadystatechange();
      }
    };
    this.send = function(data) {
      if (!navigator.javaEnabled()) {
        alert("XMLHttpRequest.send() - Java must be installed and enabled.");
        return;
      }
      if (this._async) {
        setTimeout(this._sendasync, 0, this, data);
        // this is not really asynchronous and won't execute until the current
        // execution context ends
      } else {
        this._sendsync(data);
      }
    }
    this._sendasync = function(req, data) {
      if (!req._aborted) {
        req._sendsync(data);
      }
    };
    this._sendsync = function(data) {
      this.readyState = 2;
      if (this.onreadystatechange) {
        this.onreadystatechange();
      }
      // open connection
      var url = new java.net.URL(new java.net.URL(window.location.href), this.url);
      var conn = url.openConnection();
      for (var i = 0; i < this._headers.length; i++) {
        conn.setRequestProperty(this._headers[i].h, this._headers[i].v);
      }
      this._headers = [];
      if (this.method == 'POST') {
        // POST data
        conn.setDoOutput(true);
        var wr = new java.io.OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        wr.close();
      }
      // read response headers
      // NOTE: the getHeaderField() methods always return nulls for me :(
      var gotContentEncoding = false;
      var gotContentLength = false;
      var gotContentType = false;
      var gotDate = false;
      var gotExpiration = false;
      var gotLastModified = false;
      for (var i = 0; ; i++) {
        var hdrName = conn.getHeaderFieldKey(i);
        var hdrValue = conn.getHeaderField(i);
        if (hdrName == null && hdrValue == null) {
          break;
        }
        if (hdrName != null) {
          this._headers[this._headers.length] = {h:hdrName, v:hdrValue};
          switch (hdrName.toLowerCase()) {
            case 'content-encoding': gotContentEncoding = true; break;
            case 'content-length'  : gotContentLength   = true; break;
            case 'content-type'    : gotContentType     = true; break;
            case 'date'            : gotDate            = true; break;
            case 'expires'         : gotExpiration      = true; break;
            case 'last-modified'   : gotLastModified    = true; break;
          }
        }
      }
      // try to fill in any missing header information
      var val;
      val = conn.getContentEncoding();



( run in 1.147 second using v1.01-cache-2.11-cpan-39bf76dae61 )