实现思路
- 安装 axios:如果项目未安装,通过 npm 或 yarn 安装
axios
。
- 创建表单数据:使用
FormData
对象来构造要上传的文件数据。
- 发送请求并监听进度:在 axios 的
config
中设置 onUploadProgress
回调函数,用于监听上传进度。
- 更新进度条:在
onUploadProgress
回调函数中,计算并更新进度条的显示。
关键代码片段
<template>
<div>
<input type="file" @change="handleFileChange">
<div v-if="uploading">
<progress :value="progress" :max="100"></progress>
<p>{{ progress }}%</p>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
file: null,
uploading: false,
progress: 0
};
},
methods: {
handleFileChange(e) {
this.file = e.target.files[0];
this.uploadFile();
},
uploadFile() {
this.uploading = true;
const formData = new FormData();
formData.append('file', this.file);
axios.post('/upload', formData, {
onUploadProgress: progressEvent => {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
this.progress = percentCompleted;
}
})
.then(response => {
// 上传成功处理
this.uploading = false;
this.progress = 0;
console.log('文件上传成功', response.data);
})
.catch(error => {
// 上传失败处理
this.uploading = false;
this.progress = 0;
console.error('文件上传失败', error);
});
}
}
};
</script>