MCPcopy Create free account
hub / github.com/ElemeFE/element-react / upload

Function upload

src/upload/ajax.js:31–85  ·  view source on GitHub ↗
(option)

Source from the content-addressed store, hash-verified

29}
30
31export default function upload(option) {
32 if (typeof XMLHttpRequest === 'undefined') {
33 return;
34 }
35
36 const xhr = new XMLHttpRequest();
37 const action = option.action;
38
39 if (xhr.upload) {
40 xhr.upload.onprogress = function progress(e) {
41 if (e.total > 0) {
42 e.percent = e.loaded / e.total * 100;
43 }
44 option.onProgress(e);
45 };
46 }
47
48 const formData = new FormData();
49
50 if (option.data) {
51 Object.keys(option.data).map(key => {
52 formData.append(key, option.data[key]);
53 });
54 }
55
56 formData.append(option.filename, option.file);
57
58 xhr.onerror = function error(e) {
59 option.onError(e);
60 };
61
62 xhr.onload = function onload() {
63 if (xhr.status < 200 || xhr.status >= 300) {
64 return option.onError(getError(action, option, xhr));
65 }
66
67 option.onSuccess(getBody(xhr));
68 };
69
70 xhr.open('post', action, true);
71
72 if (option.withCredentials && 'withCredentials' in xhr) {
73 xhr.withCredentials = true;
74 }
75
76 const headers = option.headers || {};
77
78 for (let item in headers) {
79 if (headers.hasOwnProperty(item) && headers[item] !== null) {
80 xhr.setRequestHeader(item, headers[item]);
81 }
82 }
83 xhr.send(formData);
84 return xhr;
85}

Callers

nothing calls this directly

Calls 6

getErrorFunction · 0.85
getBodyFunction · 0.85
appendMethod · 0.80
onProgressMethod · 0.65
onErrorMethod · 0.65
onSuccessMethod · 0.65

Tested by

no test coverage detected