-
-
Notifications
You must be signed in to change notification settings - Fork 320
/
Copy pathcustomRequest.tsx
84 lines (79 loc) · 1.75 KB
/
customRequest.tsx
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 no-console:0 */
import React from 'react';
import axios from 'axios';
import Upload from 'rc-upload';
import type { UploadRequestOption } from '@/interface';
const uploadProps = {
action: '/upload.do',
multiple: false,
data: { a: 1, b: 2 },
headers: {
Authorization: '$prefix $token',
},
onStart(file) {
console.log('onStart', file, file.name);
},
onSuccess(res, file) {
console.log('onSuccess', res, file.name);
},
onError(err) {
console.log('onError', err);
},
onProgress({ percent }, file) {
console.log('onProgress', `${percent}%`, file.name);
},
customRequest({
action,
data,
file,
filename,
headers,
onError,
onProgress,
onSuccess,
withCredentials,
}: UploadRequestOption) {
// EXAMPLE: post form-data with 'axios'
// eslint-disable-next-line no-undef
const formData = new FormData();
if (data) {
Object.keys(data).forEach(key => {
formData.append(key, data[key] as string);
});
}
formData.append(filename, file);
axios
.post(action, formData, {
withCredentials,
headers,
onUploadProgress: ({ total, loaded }) => {
onProgress({ percent: Number(Math.round((loaded / total) * 100).toFixed(2)) }, file);
},
})
.then(({ data: response }) => {
onSuccess(response, file);
})
.catch(onError);
return {
abort() {
console.log('upload progress is aborted.');
},
};
},
};
const Test = () => {
return (
<div
style={{
margin: 100,
}}
>
<div>
<Upload {...uploadProps}>
<button type="button">开始上传</button>
</Upload>
</div>
</div>
);
};
export default Test;