-
Notifications
You must be signed in to change notification settings - Fork 457
/
Copy pathFileAPI.XHR.js
365 lines (298 loc) · 9.65 KB
/
FileAPI.XHR.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/*global window, FileAPI, Uint8Array */
(function (window, api){
"use strict";
var
noop = function (){}
, document = window.document
, XHR = function (options){
this.uid = api.uid();
this.xhr = {
abort: noop
, getResponseHeader: noop
, getAllResponseHeaders: noop
};
this.options = options;
},
_xhrResponsePostfix = { '': 1, XML: 1, Text: 1, Body: 1 }
;
XHR.prototype = {
status: 0,
statusText: '',
constructor: XHR,
getResponseHeader: function (name){
return this.xhr.getResponseHeader(name);
},
getAllResponseHeaders: function (){
return this.xhr.getAllResponseHeaders() || {};
},
end: function (status, statusText){
var _this = this, options = _this.options;
_this.end =
_this.abort = noop;
_this.status = status;
if( statusText ){
_this.statusText = statusText;
}
api.log('xhr.end:', status, statusText);
options.complete(status == 200 || status == 201 ? false : _this.statusText || 'unknown', _this);
if( _this.xhr && _this.xhr.node ){
setTimeout(function (){
var node = _this.xhr.node;
try { node.parentNode.removeChild(node); } catch (e){}
try { delete window[_this.uid]; } catch (e){}
window[_this.uid] = _this.xhr.node = null;
}, 9);
}
},
abort: function (){
this.end(0, 'abort');
if( this.xhr ){
this.xhr.aborted = true;
this.xhr.abort();
}
},
send: function (FormData){
var _this = this, options = this.options;
FormData.toData(function (data){
// Start uploading
options.upload(options, _this);
_this._send.call(_this, options, data);
}, options);
},
_send: function (options, data){
var _this = this, xhr, uid = _this.uid, url = options.url;
api.log('XHR._send:', data);
if( !options.cache ){
// No cache
url += (~url.indexOf('?') ? '&' : '?') + api.uid();
}
if( data.nodeName ){
var jsonp = options.jsonp;
// prepare callback in GET
url = url.replace(/([a-z]+)=(\?)/i, '$1='+uid);
// legacy
options.upload(options, _this);
xhr = document.createElement('div');
xhr.innerHTML = '<form target="'+ uid +'" action="'+ url +'" method="POST" enctype="multipart/form-data" style="position: absolute; top: -1000px; overflow: hidden; width: 1px; height: 1px;">'
+ '<iframe name="'+ uid +'" src="javascript:false;"></iframe>'
+ (jsonp && (options.url.indexOf('=?') == -1) ? '<input value="'+ uid +'" name="'+jsonp+'" type="hidden"/>' : '')
+ '</form>'
;
// get form-data & transport
var
form = xhr.getElementsByTagName('form')[0]
, transport = xhr.getElementsByTagName('iframe')[0]
;
form.appendChild(data);
api.log(form.parentNode.innerHTML);
// append to DOM
document.body.appendChild(xhr);
// keep a reference to node-transport
_this.xhr.node = xhr;
var
onPostMessage = function (evt){
if( url.indexOf(evt.origin) != -1 ){
try {
var result = api.parseJSON(evt.data);
if( result.id == uid ){
complete(result.status, result.statusText, result.response);
}
} catch( err ){
complete(0, err.message);
}
}
},
// jsonp-callack
complete = window[uid] = function (status, statusText, response){
_this.readyState = 4;
_this.responseText = response;
_this.end(status, statusText);
api.event.off(window, 'message', onPostMessage);
window[uid] = xhr = transport = transport.onload = null;
}
;
_this.xhr.abort = function (){
try {
if( transport.stop ){ transport.stop(); }
else if( transport.contentWindow.stop ){ transport.contentWindow.stop(); }
else { transport.contentWindow.document.execCommand('Stop'); }
}
catch (er) {}
complete(0, "abort");
};
api.event.on(window, 'message', onPostMessage);
transport.onload = function (){
try {
var
win = transport.contentWindow
, doc = win.document
, result = win.result || api.parseJSON(doc.body.innerHTML)
;
complete(result.status, result.statusText, result.response);
} catch (e){}
};
// send
_this.readyState = 2; // loaded
form.submit();
form = null;
}
else {
// Clean url
url = url.replace(/([a-z]+)=(\?)&?/i, '');
// html5
if (this.xhr && this.xhr.aborted) {
api.log("Error: already aborted");
return;
}
xhr = _this.xhr = api.getXHR();
if (data.params) {
url += (url.indexOf('?') < 0 ? "?" : "&") + data.params.join("&");
}
xhr.open('POST', url, true);
if( api.withCredentials ){
xhr.withCredentials = "true";
}
if( !options.headers || !options.headers['X-Requested-With'] ){
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
api.each(options.headers, function (val, key){
xhr.setRequestHeader(key, val);
});
if ( options._chunked ) {
// chunked upload
if( xhr.upload ){
xhr.upload.addEventListener('progress', api.throttle(function (/**Event*/evt){
if (!data.retry) {
// show progress only for correct chunk uploads
options.progress({
type: evt.type
, total: data.size
, loaded: data.start + evt.loaded
, totalSize: data.size
}, _this, options);
}
}, 100), false);
}
xhr.onreadystatechange = function (){
var lkb = parseInt(xhr.getResponseHeader('X-Last-Known-Byte'), 10);
_this.status = xhr.status;
_this.statusText = xhr.statusText;
_this.readyState = xhr.readyState;
if( xhr.readyState == 4 ){
for( var k in _xhrResponsePostfix ){
_this['response'+k] = xhr['response'+k];
}
xhr.onreadystatechange = null;
if (!xhr.status || xhr.status - 201 > 0) {
api.log("Error: " + xhr.status);
// some kind of error
// 0 - connection fail or timeout, if xhr.aborted is true, then it's not recoverable user action
// up - server error
if (((!xhr.status && !xhr.aborted) || 500 == xhr.status || 416 == xhr.status) && ++data.retry <= options.chunkUploadRetry) {
// let's try again the same chunk
// only applicable for recoverable error codes 500 && 416
var delay = xhr.status ? 0 : api.chunkNetworkDownRetryTimeout;
// inform about recoverable problems
options.pause(data.file, options);
// smart restart if server reports about the last known byte
api.log("X-Last-Known-Byte: " + lkb);
if (lkb) {
data.end = lkb;
} else {
data.end = data.start - 1;
if (416 == xhr.status) {
data.end = data.end - options.chunkSize;
}
}
setTimeout(function () {
_this._send(options, data);
}, delay);
} else {
// no mo retries
_this.end(xhr.status);
}
} else {
// success
data.retry = 0;
if (data.end == data.size - 1) {
// finished
_this.end(xhr.status);
} else {
// next chunk
// shift position if server reports about the last known byte
api.log("X-Last-Known-Byte: " + lkb);
if (lkb) {
data.end = lkb;
}
data.file.FileAPIReadPosition = data.end;
setTimeout(function () {
_this._send(options, data);
}, 0);
}
}
xhr = null;
}
};
data.start = data.end + 1;
data.end = Math.max(Math.min(data.start + options.chunkSize, data.size) - 1, data.start);
// Retrieve a slice of file
var
file = data.file
, slice = (file.slice || file.mozSlice || file.webkitSlice)(data.start, data.end + 1)
;
if( data.size && !slice.size ){
setTimeout(function (){
_this.end(-1);
});
} else {
xhr.setRequestHeader("Content-Range", "bytes " + data.start + "-" + data.end + "/" + data.size);
xhr.setRequestHeader("Content-Disposition", 'attachment; filename=' + encodeURIComponent(data.name));
xhr.setRequestHeader("Content-Type", data.type || "application/octet-stream");
xhr.send(slice);
}
xhr.send(slice);
file = slice = null;
} else {
// single piece upload
if( xhr.upload ){
// https://github.com/blueimp/jQuery-File-Upload/wiki/Fixing-Safari-hanging-on-very-high-speed-connections-%281Gbps%29
xhr.upload.addEventListener('progress', api.throttle(function (/**Event*/evt){
options.progress(evt, _this, options);
}, 100), false);
}
xhr.onreadystatechange = function (){
_this.status = xhr.status;
_this.statusText = xhr.statusText;
_this.readyState = xhr.readyState;
if( xhr.readyState == 4 ){
for( var k in _xhrResponsePostfix ){
_this['response'+k] = xhr['response'+k];
}
xhr.onreadystatechange = null;
_this.end(xhr.status);
xhr = null;
}
};
if( api.isArray(data) ){
// multipart
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=_'+api.expando);
data = data.join('') +'--_'+ api.expando +'--';
/** @namespace xhr.sendAsBinary https://developer.mozilla.org/ru/XMLHttpRequest#Sending_binary_content */
if( xhr.sendAsBinary ){
xhr.sendAsBinary(data);
}
else {
var bytes = Array.prototype.map.call(data, function(c){ return c.charCodeAt(0) & 0xff; });
xhr.send(new Uint8Array(bytes).buffer);
}
} else {
// FormData
xhr.send(data);
}
}
}
}
};
// @export
api.XHR = XHR;
})(window, FileAPI);