vue实现上传图片进度
实现上传图片进度的步骤
使用 Vue 结合 Axios 或原生 XMLHttpRequest 实现上传图片进度功能。
安装 Axios(如未安装)
npm install axios
使用 Axios 实现上传进度
模板部分
<template>
<div>
<input type="file" @change="handleFileChange" accept="image/*" />
<button @click="uploadFile">上传</button>
<div v-if="progress >= 0">
上传进度: {{ progress }}%
</div>
</div>
</template>
脚本部分
<script>
import axios from 'axios';
export default {
data() {
return {
file: null,
progress: -1
};
},
methods: {
handleFileChange(event) {
this.file = event.target.files[0];
},
uploadFile() {
if (!this.file) return;
const formData = new FormData();
formData.append('file', this.file);
axios.post('你的上传接口URL', formData, {
onUploadProgress: (progressEvent) => {
if (progressEvent.lengthComputable) {
this.progress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
}
}
}).then(response => {
console.log('上传成功', response);
}).catch(error => {
console.error('上传失败', error);
});
}
}
};
</script>
使用原生 XMLHttpRequest 实现上传进度
脚本部分
methods: {
uploadFile() {
if (!this.file) return;
const formData = new FormData();
formData.append('file', this.file);
const xhr = new XMLHttpRequest();
xhr.open('POST', '你的上传接口URL', true);
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
this.progress = Math.round((event.loaded / event.total) * 100);
}
};
xhr.onload = () => {
if (xhr.status === 200) {
console.log('上传成功', xhr.response);
} else {
console.error('上传失败', xhr.statusText);
}
};
xhr.send(formData);
}
}
进度条 UI 优化
可以使用第三方 UI 库(如 Element UI)的进度条组件提升用户体验。
Element UI 进度条示例
<el-progress :percentage="progress" v-if="progress >= 0"></el-progress>
注意事项
- 确保后端接口支持文件上传并返回正确的响应。
- 处理上传失败的情况,提供用户反馈。
- 对于大文件上传,可能需要分片或断点续传功能。







