实现思路
- 使用Axios的请求配置:Axios在上传文件时提供了
onUploadProgress
回调,可通过该回调获取上传进度。
- 在Vue组件中定义数据:用于存储上传进度,以便在模板中展示进度条。
- 处理暂停和继续操作:可以通过控制Axios请求的取消来实现暂停,通过重新发起请求实现继续。
关键代码片段
- Vue组件模板
<template>
<div>
<input type="file" @change="handleFileChange">
<button @click="uploadFile">上传</button>
<button @click="pauseUpload">暂停</button>
<button @click="resumeUpload">继续</button>
<div v-if="uploading">
<progress :value="progress" :max="100"></progress>
<span>{{ progress }}%</span>
</div>
</div>
</template>
- Vue组件脚本
import axios from 'axios';
export default {
data() {
return {
file: null,
uploading: false,
progress: 0,
cancelTokenSource: null
};
},
methods: {
handleFileChange(event) {
this.file = event.target.files[0];
},
uploadFile() {
this.uploading = true;
this.cancelTokenSource = axios.CancelToken.source();
const formData = new FormData();
formData.append('file', this.file);
axios.post('/upload', formData, {
onUploadProgress: progressEvent => {
this.progress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
},
cancelToken: this.cancelTokenSource.token
})
.then(response => {
console.log('上传成功', response);
this.uploading = false;
this.progress = 0;
})
.catch(error => {
if (axios.isCancel(error)) {
console.log('上传已取消');
} else {
console.log('上传失败', error);
this.uploading = false;
this.progress = 0;
}
});
},
pauseUpload() {
if (this.cancelTokenSource) {
this.cancelTokenSource.cancel('上传已暂停');
this.uploading = false;
}
},
resumeUpload() {
if (!this.file) return;
this.uploading = true;
this.uploadFile();
}
}
};
暂停和继续操作说明
- 暂停:在
pauseUpload
方法中,通过调用cancelTokenSource.cancel
方法取消Axios请求,从而暂停上传。同时更新uploading
状态为false
。
- 继续:在
resumeUpload
方法中,先检查是否有选择的文件,若有则重新调用uploadFile
方法,重新发起上传请求,实现继续上传。