antdesign+vue+ts自定义上传文件customRequest,显示进度条onProgress,axios请求中断axios.CancelToken。
在使用Ant Design Vue的<a-upload>
组件时,可以通过customRequest
属性自定义文件上传的行为。以下是一个使用axios实现自定义上传并显示进度条的例子:
<template>
<a-upload
:customRequest="customRequest"
@change="handleChange"
>
<a-button> <a-icon type="upload" /> Click to Upload </a-button>
</a-upload>
<a-progress :percent="progress" :status="progressStatus" />
</template>
<script lang="ts">
import axios, { CancelToken, CancelTokenSource } from 'axios';
import { UploadChangeParam } from 'ant-design-vue/types/upload';
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const progress = ref<number>(0);
const progressStatus = ref<string>('active');
let cancelTokenSource: CancelTokenSource;
const customRequest = (options: any) => {
const { onProgress, onError, onSuccess, file } = options;
const formData = new FormData();
formData.append('file', file);
cancelTokenSource = CancelToken.source();
axios.post('/upload/endpoint', formData, {
onUploadProgress: (e) => {
onProgress({
percent: Math.round((e.loaded / e.total) * 100),
});
},
cancelToken: cancelTokenSource.token,
})
.then(onSuccess)
.catch(onError);
};
const handleChange = (info: UploadChangeParam) => {
if (info.event) {
const progressInfo = info.event;
progress.value = Math.round((progressInfo.loaded / progressInfo.total) * 100);
if (progressInfo.loaded === progressInfo.total) {
progressStatus.value = 'success';
}
}
};
return {
customRequest,
handleChange,
progress,
progressStatus,
};
},
});
</script>
在这个例子中,我们定义了一个customRequest
函数,它接收上传的选项作为参数。我们使用axios
的post
方法来上传文件,并通过onUploadProgress
回调跟踪上传进度。每次文件状态变化时,我们更新进度条的状态。handleChange
方法用于处理文件状态变化,并更新进度条的显示。使用<a-progress>
组件来显示实际的进度。
评论已关闭