1 | 'use strict';
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports["default"] = upload;
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | function getError(option, xhr) {
|
12 | var msg = 'cannot post ' + option.action + ' ' + xhr.status + '\'';
|
13 | var err = new Error(msg);
|
14 | err.status = xhr.status;
|
15 | err.method = 'post';
|
16 | err.url = option.action;
|
17 | return err;
|
18 | }
|
19 |
|
20 | function getBody(xhr) {
|
21 | var text = xhr.responseText || xhr.response;
|
22 | if (!text) {
|
23 | return text;
|
24 | }
|
25 |
|
26 | try {
|
27 | return JSON.parse(text);
|
28 | } catch (e) {
|
29 | return text;
|
30 | }
|
31 | }
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | function upload(option) {
|
45 | var xhr = new XMLHttpRequest();
|
46 | if (xhr.upload) {
|
47 | xhr.upload.onprogress = function progress(e) {
|
48 | if (e.total > 0) {
|
49 | e.percent = e.loaded / e.total * 100;
|
50 | }
|
51 | option.onProgress(e);
|
52 | };
|
53 | }
|
54 |
|
55 | var formData = new FormData();
|
56 |
|
57 | if (option.data) {
|
58 | Object.keys(option.data).map(function (key) {
|
59 | formData.append(key, option.data[key]);
|
60 | });
|
61 | }
|
62 |
|
63 | formData.append(option.filename, option.file);
|
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));
|
77 | };
|
78 |
|
79 | xhr.open('post', option.action, true);
|
80 |
|
81 |
|
82 | if (option.withCredentials && 'withCredentials' in xhr) {
|
83 | xhr.withCredentials = true;
|
84 | }
|
85 |
|
86 | var headers = option.headers || {};
|
87 |
|
88 |
|
89 |
|
90 | if (headers['X-Requested-With'] !== null) {
|
91 | xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
|
92 | }
|
93 |
|
94 | for (var h in headers) {
|
95 | if (headers.hasOwnProperty(h) && headers[h] !== null) {
|
96 | xhr.setRequestHeader(h, headers[h]);
|
97 | }
|
98 | }
|
99 | xhr.send(formData);
|
100 |
|
101 | return {
|
102 | abort: function abort() {
|
103 | xhr.abort();
|
104 | }
|
105 | };
|
106 | }
|
107 | module.exports = exports['default']; |
\ | No newline at end of file |