1 | 'use strict';
|
2 |
|
3 | exports.__esModule = true;
|
4 | exports.default = upload;
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | function getError(option, xhr, msg) {
|
10 | msg = msg || 'cannot post ' + option.action + ' ' + xhr.status + '\'';
|
11 | var err = new Error(msg);
|
12 | err.status = xhr.status;
|
13 | err.method = option.method;
|
14 | err.url = option.action;
|
15 | return err;
|
16 | }
|
17 |
|
18 | function getBody(xhr) {
|
19 | var text = xhr.responseText || xhr.response;
|
20 | if (!text) {
|
21 | return text;
|
22 | }
|
23 |
|
24 | try {
|
25 | return JSON.parse(text);
|
26 | } catch (e) {
|
27 | return text;
|
28 | }
|
29 | }
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | function upload(option) {
|
45 | var xhr = new XMLHttpRequest();
|
46 |
|
47 | if (option.onProgress && xhr.upload) {
|
48 | xhr.upload.onprogress = function progress(e) {
|
49 | if (e.total > 0) {
|
50 | e.percent = e.loaded / e.total * 100;
|
51 | }
|
52 | option.onProgress(e);
|
53 | };
|
54 | }
|
55 |
|
56 | var formData = new FormData();
|
57 |
|
58 | if (option.data) {
|
59 | Object.keys(option.data).forEach(function (key) {
|
60 | formData.append(key, option.data[key]);
|
61 | });
|
62 | }
|
63 | if (option.file instanceof Blob) {
|
64 | formData.append(option.filename, option.file, option.file.name);
|
65 | } else {
|
66 | formData.append(option.filename, option.file);
|
67 | }
|
68 |
|
69 | xhr.onerror = function error(e) {
|
70 | option.onError(e);
|
71 | };
|
72 |
|
73 | xhr.onload = function onload() {
|
74 |
|
75 |
|
76 | if (xhr.status < 200 || xhr.status >= 300) {
|
77 | return option.onError(getError(option, xhr), getBody(xhr));
|
78 | }
|
79 |
|
80 | option.onSuccess(getBody(xhr), xhr);
|
81 | };
|
82 |
|
83 | option.method = option.method || 'POST';
|
84 | xhr.open(option.method, option.action, true);
|
85 |
|
86 |
|
87 |
|
88 | var timeout = option.timeout;
|
89 |
|
90 |
|
91 | if (typeof timeout === 'number' && timeout > 0) {
|
92 | xhr.timeout = timeout;
|
93 | xhr.ontimeout = function () {
|
94 | var msg = 'Upload abort for exceeding time (timeout: ' + timeout + 'ms)';
|
95 | option.onError(getError(option, xhr, msg), getBody(xhr));
|
96 | };
|
97 | }
|
98 |
|
99 |
|
100 | if (option.withCredentials && 'withCredentials' in xhr) {
|
101 | xhr.withCredentials = true;
|
102 | }
|
103 |
|
104 | var headers = option.headers || {};
|
105 |
|
106 |
|
107 |
|
108 | if (headers['X-Requested-With'] !== null) {
|
109 | xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
|
110 | }
|
111 |
|
112 | for (var h in headers) {
|
113 | if (headers.hasOwnProperty(h) && headers[h] !== null) {
|
114 | xhr.setRequestHeader(h, headers[h]);
|
115 | }
|
116 | }
|
117 | xhr.send(formData);
|
118 |
|
119 | return {
|
120 | abort: function abort() {
|
121 | xhr.abort();
|
122 | }
|
123 | };
|
124 | }
|
125 | module.exports = exports['default']; |
\ | No newline at end of file |