-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileUpload.js
executable file
·89 lines (81 loc) · 2.21 KB
/
FileUpload.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
85
86
87
88
89
var getError = function (options, xhr) {
var msg = 'cannot post ' + options.url + ":" + xhr.status;
var err = new Error(msg);
err.status = xhr.status;
err.method = 'post';
err.url = options.url;
return err;
}
var getBody = function (xhr) {
var text = xhr.responseText || xhr.response;
if (!text) {
return text;
}
try {
return JSON.parse(text);
} catch (e) {
return text;
}
}
var Uploader = {
post: function (options) {
if (typeof XMLHttpRequest === 'undefined') {
return;
}
var xhr = new XMLHttpRequest();
if (xhr.upload) {
xhr.upload.onprogress = function (e) {
if (e.total > 0) {
e.percent = e.loaded / e.total * 100;
}
options.onLoad(e);
}
}
var formData = new FormData();
if (options.data) {
for (var i in options.data) {
formData.append(i, options.data[i]);
}
}
formData.append(options.filename, options.file);
xhr.onerror = function (e) {
options.onEnd(e);
options.onError(e);
}
xhr.onload = function (e) {
if (xhr.status !== 200) {
options.onEnd(e);
return options.onError(getError(options, xhr), getBody(xhr));
}
options.onEnd(e);
options.onSuccess(getBody(xhr));
}
xhr.open('post', options.url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
if (options.header) {
for (var i in options.header) {
xhr.setRequestHeader(i, options.header[i]);
}
}
xhr.send(formData);
}
}
module.exports = {
uploadFile: function (options) {
options.url = options.url || "/upload";
options.filename = options.filename || "file";
options.beforeUpload = options.beforeUpload || function (e) { return true; };
options.onSuccess = options.onSuccess || function (e) { };
options.onError = options.onError || function (e) { };
options.onLoad = options.onLoad || function (e) { };
options.onStart = options.onStart || function (e) { };
options.onEnd = options.onEnd || function (e) { };
if (options.beforeUpload(options)) {
options.onStart(options);
// 开始上传文件
Uploader.post(options);
}
},
uploadFiles: function (options) {
}
}