vue实现上传进度
Vue 实现文件上传进度
在 Vue 中实现文件上传进度可以通过 XMLHttpRequest 或 axios 的 onUploadProgress 事件来监听上传进度。以下是两种常见实现方式:
使用 XMLHttpRequest 实现
通过原生 XMLHttpRequest 对象的 upload 属性监听进度事件:

// 在 Vue 方法中
uploadFile(file) {
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('file', file);
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
const percent = Math.round((event.loaded / event.total) * 100);
this.uploadProgress = percent; // 更新进度状态
}
});
xhr.open('POST', '/api/upload', true);
xhr.send(formData);
}
模板中显示进度:

<progress :value="uploadProgress" max="100"></progress>
<span>{{ uploadProgress }}%</span>
使用 Axios 实现
Axios 提供了 onUploadProgress 回调,更适合 Vue 项目:
import axios from 'axios';
// 在 Vue 方法中
async uploadFile(file) {
const formData = new FormData();
formData.append('file', file);
try {
const response = await axios.post('/api/upload', formData, {
onUploadProgress: (progressEvent) => {
const percent = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
this.uploadProgress = percent;
},
});
console.log('上传成功', response.data);
} catch (error) {
console.error('上传失败', error);
}
}
组件化实现示例
封装一个可复用的上传组件:
<template>
<div>
<input type="file" @change="handleFileChange" />
<button @click="uploadFile">上传</button>
<div v-if="uploadProgress > 0">
<progress :value="uploadProgress" max="100"></progress>
{{ uploadProgress }}%
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedFile: null,
uploadProgress: 0,
};
},
methods: {
handleFileChange(event) {
this.selectedFile = event.target.files[0];
},
async uploadFile() {
if (!this.selectedFile) return;
const formData = new FormData();
formData.append('file', this.selectedFile);
try {
await axios.post('/api/upload', formData, {
onUploadProgress: (progressEvent) => {
this.uploadProgress = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
},
});
this.$emit('upload-success');
} catch (error) {
this.$emit('upload-error', error);
}
},
},
};
</script>
注意事项
- 跨域问题:确保后端支持 CORS 并正确配置
Access-Control-Allow-Origin。 - 文件大小限制:后端需处理大文件上传(如分片上传)。
- 进度准确性:部分服务器可能无法返回准确的
content-length,需测试验证。 - UI 反馈:建议结合加载状态或错误提示(如
v-if="uploadProgress === 100")。
通过上述方法,可以轻松在 Vue 中实现文件上传进度功能。






