Skip to content

Commit a787d59

Browse files
committed
+ xhr-promise
2 parents d717c76 + d8d494d commit a787d59

File tree

6 files changed

+252
-30
lines changed

6 files changed

+252
-30
lines changed

README.md

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ FileAPI.event.on(document, 'drop', function (evt/**Event*/){
178178
---
179179

180180
<a name="FileAPI.upload"></a>
181-
### upload(opts`:Object`)`:XmlHttpRequest`
181+
### upload(opts`:Object`)`:XmlHttpRequestPromise`
182182
Uploading files to the server (successively). Returns XHR-like object.
183183
It is important to remember to correctly worked flash-transport server response body must not be empty,
184184
for example, you can pass, just text "ok".
@@ -633,9 +633,70 @@ The type (MIME type) of the file referenced by the File object.
633633
### size
634634
The size (in bytes) of the file referenced by the File object.
635635

636+
---
637+
638+
<a name="XmlHttpRequestPromise"></a>
639+
## XmlHttpRequestPromise
640+
641+
<a name="XmlHttpRequestPromise.status"></a>
642+
### status`:Number`
643+
The status of the response to the request. This is the HTTP result code (for example, status is 200 for a successful request).
644+
645+
---
646+
647+
<a name="XmlHttpRequestPromise.statusText"></a>
648+
### statusText`:String`
649+
The response string returned by the HTTP server. Unlike status, this includes the entire text of the response message ("200 OK", for example).
650+
651+
---
652+
653+
<a name="XmlHttpRequestPromise.responseXML"></a>
654+
### responseXML`:Document`
655+
The response to the request as a DOM Document object, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. The response is parsed as if it were a text/xml stream. When the responseType is set to "document" and the request has been made asynchronously, the response is parsed as it were a text/html stream.
656+
657+
---
658+
659+
<a name="XmlHttpRequestPromise.responseText"></a>
660+
### responseText`:String`
661+
The response to the request as text, or null if the request was unsuccessful or has not yet been sent.
662+
663+
---
664+
665+
<a name="XmlHttpRequestPromise.abort"></a>
666+
### abort()`:void`
667+
Aborts the request if it has already been sent.
636668

637669
---
638670

671+
<a name="XmlHttpRequestPromise.getAllResponseHeaders"></a>
672+
### getAllResponseHeaders()`:String`
673+
Returns all the response headers as a string, or null if no response has been received.
674+
675+
---
676+
677+
<a name="XmlHttpRequestPromise.getResponseHeader"></a>
678+
### getResponseHeader(name`:String`)`:String`
679+
Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response.
680+
681+
* name — header name
682+
683+
---
684+
685+
<a name="XmlHttpRequestPromise.success"></a>
686+
### success(callback`:Function`)`:XmlHttpRequestPromise`
687+
A function to be called if the request succeeds.
688+
689+
* callback — receives two arguments: `xhr` and `options`
690+
691+
---
692+
693+
<a name="XmlHttpRequestPromise.error"></a>
694+
### error(callback`:Function`)`:XmlHttpRequestPromise`
695+
A function to be called if the request succeeds.
696+
697+
* callback — receives three arguments: `error`, `xhr` and `options`
698+
699+
---
639700

640701
<a name="FileAPI.event"></a>
641702
## FileAPI.event

README.ru.md

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ FileAPI.event.on(document, 'drop', function (evt/**Event*/){
177177
---
178178

179179
<a name="FileAPI.upload"></a>
180-
### upload(opts`:Object`)`:XmlHttpRequest`
180+
### upload(opts`:Object`)`:XmlHttpRequestPromise`
181181
Загрузка файлов на сервер (последовательно). Возвращает XHR-подобный объект.
182182
Помните, для корректной работы flash-транспорта, тело ответа сервера не должно быть пустым,
183183
например можно ответить простым текстом "ok".
@@ -616,6 +616,71 @@ MIME type
616616
Размер файла в байтах.
617617

618618

619+
---
620+
621+
<a name="XmlHttpRequestPromise"></a>
622+
## XmlHttpRequestPromise
623+
624+
625+
<a name="XmlHttpRequestPromise.status"></a>
626+
### status`:Number`
627+
HTTP-статус в виде числа (404 — «Not Found», 200 — «OK» и т. д.)
628+
629+
---
630+
631+
<a name="XmlHttpRequestPromise.statusText"></a>
632+
### statusText`:String`
633+
Статус в виде строки («Not Found», «OK» и т. д.).
634+
635+
---
636+
637+
<a name="XmlHttpRequestPromise.responseXML"></a>
638+
### responseXML`:Document`
639+
Текст ответа на запрос в виде XML, который затем может быть обработан посредством DOM.
640+
641+
---
642+
643+
<a name="XmlHttpRequestPromise.responseText"></a>
644+
### responseText`:String`
645+
Текст ответа на запрос.
646+
647+
---
648+
649+
<a name="XmlHttpRequestPromise.abort"></a>
650+
### abort()`:void`
651+
Отменяет текущий запрос, удаляет все заголовки, ставит текст ответа сервера в null.
652+
653+
---
654+
655+
<a name="XmlHttpRequestPromise.getAllResponseHeaders"></a>
656+
### getAllResponseHeaders()`:String`
657+
Возвращает полный список HTTP-заголовков в виде строки.
658+
659+
---
660+
661+
<a name="XmlHttpRequestPromise.getResponseHeader"></a>
662+
### getResponseHeader(name`:String`)`:String`
663+
Возвращает значение указанного заголовка. Если заголовок не найден, возвращает null.
664+
665+
* name — имя заголовка
666+
667+
---
668+
669+
<a name="XmlHttpRequestPromise.success"></a>
670+
### success(callback`:Function`)`:XmlHttpRequestPromise`
671+
Функция, которая исполняется в случае неудачного запроса.
672+
673+
* callback — принимает два аргумента: `xhr` и `options`
674+
675+
---
676+
677+
<a name="XmlHttpRequestPromise.error"></a>
678+
### error(callback`:Function`)`:XmlHttpRequestPromise`
679+
Функция, которая исполняется в случае успешного запроса.
680+
681+
* callback — принимает три аргумента: `error`, `xhr` и `options`
682+
683+
619684
---
620685

621686

examples/demo.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
, staticPath: '../dist/'
2929
};
3030
</script>
31-
<script src="../dist/FileAPI.min.js"></script>
31+
<script src="../dist/FileAPI.js"></script>
3232
<script src="../plugins/FileAPI.id3.js"></script>
3333
<script src="../plugins/FileAPI.exif.js"></script>
3434

lib/FileAPI.core.js

Lines changed: 91 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,8 @@
2020
FileReader = window.FileReader,
2121
FormData = window.FormData,
2222

23-
24-
XMLHttpRequest = window.XMLHttpRequest,
2523
jQuery = window.jQuery,
24+
XMLHttpRequest = window.XMLHttpRequest,
2625

2726
html5 = !!(File && (FileReader && (window.Uint8Array || FormData || XMLHttpRequest.prototype.sendAsBinary)))
2827
&& !(/safari\//i.test(userAgent) && !/chrome\//i.test(userAgent) && /windows/i.test(userAgent)), // BugFix: https://github.com/mailru/FileAPI/issues/25
@@ -34,15 +33,15 @@
3433
// https://github.com/blueimp/JavaScript-Canvas-to-Blob
3534
dataURLtoBlob = window.dataURLtoBlob,
3635

37-
3836
_rimg = /img/i,
3937
_rcanvas = /canvas/i,
4038
_rimgcanvas = /img|canvas/i,
4139
_rinput = /input/i,
4240
_rdata = /^data:[^,]+,/,
4341

44-
4542
Math = window.Math,
43+
setTimeout = window.setTimeout,
44+
clearTimeout = window.clearTimeout,
4645

4746
_SIZE_CONST = function (pow){
4847
pow = new window.Number(Math.pow(1024, pow));
@@ -349,26 +348,75 @@
349348
*/
350349
defer: function (){
351350
var
352-
list = []
353-
, result
354-
, error
351+
doneList = []
352+
, failList = []
353+
, progressList = []
354+
355+
, _push = function (x, fn){
356+
(x ? doneList : failList).push(fn);
357+
return this;
358+
}
359+
360+
, _complete = function (state, args){
361+
var
362+
list = state ? doneList : failList
363+
, i = 0, n = list.length
364+
;
365+
366+
_push = function (x, fn){
367+
(x === state) && fn.apply(this, args);
368+
};
369+
370+
_complete = noop;
371+
372+
doneList =
373+
failList =
374+
progressList = null;
375+
376+
for( ; i < n; i++ ){
377+
list[i] && list[i].apply(this, args);
378+
}
379+
}
380+
355381
, defer = {
356-
resolve: function (err, res){
357-
defer.resolve = noop;
358-
error = err || false;
359-
result = res;
382+
done: function (fn){
383+
_push(1, fn);
384+
return this;
385+
},
360386

361-
while( res = list.shift() ){
362-
res(error, result);
363-
}
387+
fail: function (fn){
388+
_push(0, fn);
389+
return this;
390+
},
391+
392+
resolve: function (){
393+
_complete(1, arguments);
394+
return this;
364395
},
365396

366-
then: function (fn){
367-
if( error !== undef ){
368-
fn(error, result);
369-
} else {
370-
list.push(fn);
397+
reject: function (){
398+
_complete(0, arguments);
399+
return this;
400+
},
401+
402+
notify: function (){
403+
var i = 0, n = progressList.length;
404+
for( ; i< n; i++ ){
405+
progressList[i].apply(this, arguments);
371406
}
407+
},
408+
409+
progress: function (fn){
410+
progressList.push(fn);
411+
return this;
412+
},
413+
414+
then: function (doneFn, failFn){
415+
return defer.done(doneFn).fail(failFn);
416+
},
417+
418+
promise: function (){
419+
return this;
372420
}
373421
};
374422

@@ -411,6 +459,7 @@
411459
}
412460
}
413461
;
462+
414463
return queue;
415464
},
416465

@@ -936,6 +985,8 @@
936985
var
937986
proxyXHR = new api.XHR(options)
938987
, dataArray = _getUploadFiles(options.files, options.postName)
988+
, defer = api.defer()
989+
939990
, _this = this
940991
, _total = 0
941992
, _loaded = 0
@@ -963,6 +1014,11 @@
9631014
// emit "beforeupload" event
9641015
options.beforeupload(proxyXHR, options);
9651016

1017+
// Subscribe to `defer`
1018+
defer.progress(options.progress);
1019+
defer.done(options.success);
1020+
defer.fail(options.error);
1021+
9661022
// Upload by file
9671023
_nextFile = function (){
9681024
var
@@ -1015,7 +1071,7 @@
10151071
}, _file, xhr, _fileOptions);
10161072

10171073
// emit "progress" event
1018-
options.progress({
1074+
defer.notify({
10191075
type: 'progress'
10201076
, total: _total
10211077
, loaded: proxyXHR.loaded = (_loaded + data.size * (evt.loaded/evt.total))|0
@@ -1063,7 +1119,16 @@
10631119
});
10641120
}
10651121
else {
1066-
options.complete(proxyXHR.status == 200 || proxyXHR.status == 201 ? false : (proxyXHR.statusText || 'error'), proxyXHR, options);
1122+
var err = proxyXHR.status == 200 || proxyXHR.status == 201 ? false : (proxyXHR.statusText || 'error');
1123+
1124+
if( err ){
1125+
defer.reject(err, proxyXHR, options);
1126+
} else {
1127+
defer.resolve(proxyXHR, options);
1128+
}
1129+
1130+
options.complete(err, proxyXHR, options);
1131+
10671132
// Mark done state
10681133
_complete = true;
10691134
}
@@ -1082,7 +1147,7 @@
10821147
_each(files, function (data) {
10831148
_total += data.size;
10841149
proxyXHR.files.push(data.file);
1085-
if (first) {
1150+
if( first ){
10861151
dataArray.unshift(data);
10871152
} else {
10881153
dataArray.push(data);
@@ -1109,7 +1174,10 @@
11091174
return _file;
11101175
};
11111176

1112-
return proxyXHR;
1177+
proxyXHR.error = defer.fail;
1178+
proxyXHR.success = defer.done;
1179+
1180+
return _extend(proxyXHR, defer);
11131181
},
11141182

11151183

plugins/FileAPI.id3.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy