-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathajaxUpload.js
84 lines (70 loc) · 1.71 KB
/
ajaxUpload.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
/* eslint-disable no-prototype-builtins */
function getError(url, option, xhr) {
let msg;
if (xhr.response) {
msg = `${xhr.response.error || xhr.response}`;
} else if (xhr.responseText) {
msg = `${xhr.responseText}`;
} else {
msg = `fail to post ${url} ${xhr.status}`;
}
const err = new Error(msg);
err.status = xhr.status;
err.method = "post";
err.url = url;
return err;
}
function getBody(xhr) {
const text = xhr.responseText || xhr.response;
if (!text) {
return text;
}
try {
return JSON.parse(text);
} catch (e) {
return text;
}
}
// ajaxUpload
export default function ajaxUpload(option) {
if (typeof XMLHttpRequest === "undefined") {
return;
}
const xhr = new XMLHttpRequest();
const url = option.url;
if (xhr.upload) {
xhr.upload.onprogress = function progress(e) {
if (e.total > 0) {
e.percent = (e.loaded / e.total) * 100;
}
option.onProgress(e);
};
}
const formData = new FormData();
if (option.data) {
(option.data || []).forEach((item) => {
formData.append(option.formDataName, item);
});
}
xhr.onerror = function error(e) {
option.onError(e);
};
xhr.onload = function onload() {
if (xhr.status < 200 || xhr.status >= 300) {
return option.onError(getError(url, option, xhr));
}
option.onSuccess(getBody(xhr));
};
xhr.open("post", url, true);
if (option.withCredentials && "withCredentials" in xhr) {
xhr.withCredentials = true;
}
const headers = option.headers || {};
for (const item in headers) {
if (headers.hasOwnProperty(item) && headers[item] !== null) {
xhr.setRequestHeader(item, headers[item]);
}
}
xhr.send(formData);
return xhr;
}