vue实现文件进度
Vue 实现文件上传进度
使用 Vue 实现文件上传进度可以通过结合 axios 或原生 XMLHttpRequest 的进度事件来实现。以下是两种常见方法:

使用 axios 上传文件并显示进度
安装 axios(如果尚未安装):

npm install axios
在 Vue 组件中实现:
<template>
<div>
<input type="file" @change="handleFileUpload" />
<button @click="uploadFile">上传</button>
<div v-if="progress > 0">
上传进度:{{ progress }}%
<progress :value="progress" max="100"></progress>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
file: null,
progress: 0
};
},
methods: {
handleFileUpload(event) {
this.file = event.target.files[0];
},
uploadFile() {
if (!this.file) return;
const formData = new FormData();
formData.append('file', this.file);
axios.post('你的上传接口', formData, {
onUploadProgress: (progressEvent) => {
this.progress = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
}
}).then(response => {
console.log('上传成功', response);
}).catch(error => {
console.error('上传失败', error);
});
}
}
};
</script>
使用原生 XMLHttpRequest 实现
<template>
<!-- 同上 -->
</template>
<script>
export default {
data() {
return {
file: null,
progress: 0
};
},
methods: {
handleFileUpload(event) {
this.file = event.target.files[0];
},
uploadFile() {
if (!this.file) return;
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('file', this.file);
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
this.progress = Math.round((event.loaded / event.total) * 100);
}
});
xhr.open('POST', '你的上传接口', true);
xhr.send(formData);
}
}
};
</script>
进度条样式优化
可以使用第三方 UI 库(如 Element UI、Vuetify 等)的进度条组件替代原生 <progress> 标签。以 Element UI 为例:
<template>
<el-progress :percentage="progress" v-if="progress > 0"></el-progress>
</template>
注意事项
- 确保后端接口支持文件上传并能够正确处理
multipart/form-data格式 - 对于大文件上传,可以考虑分片上传或断点续传
- 上传进度可能因浏览器和网络环境略有差异
- 生产环境中建议添加取消上传的功能






