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