# 网络请求工具
- 基于
axios 1.4.0
封装
# 文件上传进度条
import axios, { AxiosProgressEvent } from "axios";
// 做进度条函数
const uploadProgress = (evt: AxiosProgressEvent, id: string) => {
if (evt.progress && evt.total) {
const percent = Math.round((evt.loaded * 100) / evt.total);
setProgresses({ ...progresses, [id]: percent });
}
};
const fileUpload = async (file: File) => {
const url = `${getBaseUrl()}/${FILE_UPLOAD}`;
const form = new FormData();
const { fileInfo, cid } = file;
if (fileInfo) {
form.append("file", fileInfo);
const option = {
method: "post",
url,
data: form,
onUploadProgress: (event: AxiosProgressEvent) =>
uploadProgress(event, cid),
};
try {
const result = await axios(option);
uploadedFilesUrl.current = {
...uploadedFilesUrl.current,
[cid]: result.data.data,
};
} catch (e) {
setUploadFailed([...uploadFailed, cid]);
}
}
};
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
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