antdesign上传多个文件,前端如何获取上传进度
时间: 2025-06-28 07:17:01 浏览: 11
### Ant Design Vue 实现多文件上传并获取前端上传进度
为了实现在前端使用 Ant Design Vue 进行多文件上传,并实时展示上传进度,可以按照以下方式构建组件:
#### 安装依赖库
确保项目已经安装 `ant-design-vue` 和其他必要的包。
```bash
npm install ant-design-vue axios
```
#### 创建上传组件
创建一个新的 Vue 组件来处理文件上传逻辑。该组件会利用 Axios 库发送带有进度事件监听器的 HTTP 请求。
```vue
<template>
<a-upload
:file-list="fileList"
@change="handleChange"
multiple
>
<a-button type="primary">
Click to Upload
</a-button>
</a-upload>
<!-- 显示每个文件的上传进度 -->
<div v-for="(item, index) in fileList" :key="index">
{{ item.name }}: {{ item.percent || 0 }}%
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
export default defineComponent({
data() {
return {
fileList: [] as any[],
};
},
methods: {
handleChange(info: any) {
const status = info.file.status;
if (status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (status === 'done') {
message.success(`${info.file.name} file uploaded successfully.`);
} else if (status === 'error') {
message.error(`${info.file.name} file upload failed.`);
}
this.handleUploadProgress(info.file.originFileObj); // 自定义函数用于更新进度条
},
handleUploadProgress(file: File) {
let formData = new FormData();
formData.append('files', file);
axios.post('/api/upload', formData, {
onUploadProgress: function(progressEvent) {
let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
// 更新单个文件的状态
for(let i=0;i<this.fileList.length;i++){
if(this.fileList[i].originFileObj===file){
this.$set(this.fileList,i,{
...this.fileList[i],
percent:percentCompleted,
status:'uploading'
});
break;
}
}
}.bind(this),
}).then(response => {
// 成功后的操作...
}).catch(error => {
// 错误处理...
});
}
}
});
</script>
```
此代码片段展示了如何通过监听 `onUploadProgress` 来捕获上传过程中的进度变化[^1]。每当有新的进度数据可用时,都会触发回调函数,在其中计算已完成的比例并将它设置到对应文件对象上以便于视图层能够及时反映最新的状态。
#### 关键点说明
- 使用了 `FormData` 对象封装要上传的数据。
- 利用了 Axios 的 `onUploadProgress` 配置项监控上传过程中产生的事件。
- 将进度百分比存储在 `fileList` 数组内的各个文件对应的属性里,从而可以在模板中动态渲染出来。
阅读全文
相关推荐


















