vue实现文件进度
Vue 文件上传进度实现
在 Vue 中实现文件上传进度功能通常需要结合 axios 或其他 HTTP 客户端库的进度事件。以下是具体实现方法:
使用 axios 上传文件并显示进度
安装 axios(如未安装):
npm install axios
组件代码示例:
<template>
<div>
<input type="file" @change="handleFileChange" />
<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: {
handleFileChange(event) {
this.file = event.target.files[0];
},
async uploadFile() {
if (!this.file) return;
const formData = new FormData();
formData.append('file', this.file);
try {
const response = await axios.post('your_upload_url', formData, {
onUploadProgress: (progressEvent) => {
this.progress = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
}
});
console.log('上传成功', response.data);
} catch (error) {
console.error('上传失败', error);
}
}
}
};
</script>
使用原生 XMLHttpRequest 实现
<template>
<!-- 同上 -->
</template>
<script>
export default {
data() {
return {
file: null,
progress: 0
};
},
methods: {
handleFileChange(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', 'your_upload_url', true);
xhr.send(formData);
}
}
};
</script>
使用第三方库(如 vue-upload-component)
安装:
npm install vue-upload-component
使用示例:
<template>
<file-upload
ref="upload"
v-model="files"
post-action="/upload"
@input-file="inputFile"
@input-filter="inputFilter"
@progress="onProgress"
></file-upload>
</template>
<script>
import FileUpload from 'vue-upload-component';
export default {
components: {
FileUpload
},
data() {
return {
files: [],
progress: 0
};
},
methods: {
onProgress(file) {
this.progress = file.progress;
},
// 其他必要方法...
}
};
</script>
进度条样式优化
可以使用 CSS 美化进度条:
progress {
width: 100%;
height: 8px;
border-radius: 4px;
}
progress::-webkit-progress-bar {
background-color: #f0f0f0;
border-radius: 4px;
}
progress::-webkit-progress-value {
background-color: #42b983;
border-radius: 4px;
}
注意事项
- 确保后端接口支持文件上传并返回正确的响应
- 大文件上传考虑实现分片上传
- 上传过程中禁用提交按钮防止重复提交
- 添加错误处理和上传完成后的回调逻辑







