raspberryGPIOhtmlserver/node_modules/ws/examples/fileapi/public/uploader.js
node_modules/ws/examples/fileapi/public/uploader.jsRaw
1function Uploader(url, cb) {
2 this.ws = new WebSocket(url);
3 if (cb) this.ws.onopen = cb;
4 this.sendQueue = [];
5 this.sending = null;
6 this.sendCallback = null;
7 this.ondone = null;
8 var self = this;
9 this.ws.onmessage = function(event) {
10 var data = JSON.parse(event.data);
11 if (data.event == 'complete') {
12 if (data.path != self.sending.path) {
13 self.sendQueue = [];
14 self.sending = null;
15 self.sendCallback = null;
16 throw new Error('Got message for wrong file!');
17 }
18 self.sending = null;
19 var callback = self.sendCallback;
20 self.sendCallback = null;
21 if (callback) callback();
22 if (self.sendQueue.length === 0 && self.ondone) self.ondone(null);
23 if (self.sendQueue.length > 0) {
24 var args = self.sendQueue.pop();
25 setTimeout(function() { self.sendFile.apply(self, args); }, 0);
26 }
27 }
28 else if (data.event == 'error') {
29 self.sendQueue = [];
30 self.sending = null;
31 var callback = self.sendCallback;
32 self.sendCallback = null;
33 var error = new Error('Server reported send error for file ' + data.path);
34 if (callback) callback(error);
35 if (self.ondone) self.ondone(error);
36 }
37 }
38}
39
40Uploader.prototype.sendFile = function(file, cb) {
41 if (this.ws.readyState != WebSocket.OPEN) throw new Error('Not connected');
42 if (this.sending) {
43 this.sendQueue.push(arguments);
44 return;
45 }
46 var fileData = { name: file.name, path: file.webkitRelativePath };
47 this.sending = fileData;
48 this.sendCallback = cb;
49 this.ws.send(JSON.stringify(fileData));
50 this.ws.send(file);
51}
52
53Uploader.prototype.close = function() {
54 this.ws.close();
55}