/
send.ts
108 lines (90 loc) · 2.5 KB
/
send.ts
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*!
* Jodit Editor (https://xdsoft.net/jodit/)
* Released under MIT see LICENSE.txt in the project root for license information.
* Copyright (c) 2013-2024 Valeriy Chupurnov. All rights reserved. https://xdsoft.net
*/
/**
* @module modules/uploader
*/
import type { IDictionary, IUploader, IUploaderAnswer } from 'jodit/types';
import { isFunction, isPromise } from 'jodit/core/helpers';
import { Ajax } from 'jodit/core/request';
import { buildData } from 'jodit/modules/uploader/helpers/build-data';
export const ajaxInstances: WeakMap<IUploader, Set<Ajax>> = new WeakMap();
export function send(
uploader: IUploader,
data: FormData | IDictionary<string>
): Promise<IUploaderAnswer> {
const requestData = buildData(uploader, data);
const sendData = (
request: FormData | IDictionary<string> | string
): Promise<any> => {
const ajax = new Ajax<IUploaderAnswer>({
xhr: (): XMLHttpRequest => {
const xhr = new XMLHttpRequest();
if (
(uploader.j.ow as any).FormData !== undefined &&
xhr.upload
) {
uploader.j.progressbar.show().progress(10);
xhr.upload.addEventListener(
'progress',
evt => {
if (evt.lengthComputable) {
let percentComplete = evt.loaded / evt.total;
percentComplete *= 100;
uploader.j.progressbar
.show()
.progress(percentComplete);
if (percentComplete >= 100) {
uploader.j.progressbar.hide();
}
}
},
false
);
} else {
uploader.j.progressbar.hide();
}
return xhr;
},
method: uploader.o.method || 'POST',
data: request,
url: isFunction(uploader.o.url)
? uploader.o.url(request)
: uploader.o.url,
headers: uploader.o.headers,
queryBuild: uploader.o.queryBuild,
contentType: uploader.o.contentType.call(uploader, request),
withCredentials: uploader.o.withCredentials || false
});
let instances = ajaxInstances.get(uploader);
if (!instances) {
instances = new Set<Ajax>();
ajaxInstances.set(uploader, instances);
}
instances.add(ajax);
uploader.j.e.one('beforeDestruct', ajax.destruct);
return ajax
.send()
.then(resp => resp.json())
.catch(error => {
return {
success: false,
data: {
messages: [error]
}
};
})
.finally(() => {
ajax.destruct();
instances?.delete(ajax);
});
};
if (isPromise(requestData)) {
return requestData.then(sendData).catch(error => {
uploader.o.error.call(uploader, error);
});
}
return sendData(requestData);
}