root/trunk/perlbal-uploadtrack.js

Revision 5, 2.4 kB (checked in by bradfitz, 4 years ago)

make library actually work

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1////// public interface:
2
3function UploadTracker (formele, cb) {
4    this.form      = formele;
5    this.callback = cb;
6    this.session  = UploadTracker._generateSession();
7    this.stopped  = false;
8
9    var action = this.form.action;
10    if (action.match(/\bclient_up_sess=(\w+)/)) {
11        action = action.replace(/\bclient_up_sess=(\w+)/, "client_up_sess=" + this.session);
12    } else {
13        action += (action.match(/\?/) ? "&" : "?");
14        action += "client_up_sess=" + this.session;
15    }
16    this.form.action = action;
17
18    this._startCheckStatus();
19}
20
21
22// method to stop tracking a form's upload status
23UploadTracker.prototype.stopTracking = function () {
24    this.stopped = true;
25};
26
27
28// private implementation details:
29UploadTracker._XTR = function () {
30    var xtr;
31    var ex;
32
33    if (typeof(XMLHttpRequest) != "undefined") {
34        xtr = new XMLHttpRequest();
35    } else {
36        try {
37            xtr = new ActiveXObject("Msxml2.XMLHTTP.4.0");
38        } catch (ex) {
39            try {
40                xtr = new ActiveXObject("Msxml2.XMLHTTP");
41            } catch (ex) {
42            }
43        }
44    }
45
46    // let me explain this.  Opera 8 does XMLHttpRequest, but not setRequestHeader.
47    // no problem, we thought:  we'll test for setRequestHeader and if it's not present
48    // then fall back to the old behavior (treat it as not working).  BUT --- IE6 won't
49    // let you even test for setRequestHeader without throwing an exception (you need
50    // to call .open on the .xtr first or something)
51    try {
52        if (xtr && ! xtr.setRequestHeader)
53            xtr = null;
54    } catch (ex) { }
55
56    return xtr;
57};
58
59
60UploadTracker._generateSession = function () {
61    var str = Math.random() + "";
62    return curSession = str.replace(/[^\d]/, "");
63};
64
65
66UploadTracker.prototype._startCheckStatus = function () {
67    var uptrack = this;
68    if (uptrack.stopped) return true;
69
70    var xtr = UploadTracker._XTR();
71    if (!xtr) return;
72
73    var callback = function () {
74        if (xtr.readyState != 4) return;
75        if (uptrack.stopped)     return;
76
77        if (xtr.status == 200) {
78            var val;
79            eval("val = " + xtr.responseText + ";");
80            uptrack.callback(val);
81        }
82        setTimeout(function () { uptrack._startCheckStatus(); }, 1000);
83    };
84
85    xtr.onreadystatechange = callback;
86    xtr.open("GET", "/__upload_status?client_up_sess=" + uptrack.session + "&rand=" + Math.random());
87    xtr.send(null);
88}
Note: See TracBrowser for help on using the browser.