用vue写一个上传文件组件
时间: 2023-05-31 08:05:17 浏览: 63
这是一个基本的上传文件组件,使用Vue.js和Axios库:
```
<template>
<div>
<input type="file" ref="fileInput" @change="uploadFile">
<button @click="submitFile">Submit</button>
<progress v-if="uploadProgress > 0" :value="uploadProgress" max="100"></progress>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
file: null,
uploadProgress: 0
}
},
methods: {
uploadFile() {
this.file = this.$refs.fileInput.files[0];
},
submitFile() {
let formData = new FormData();
formData.append('file', this.file);
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: (progressEvent) => {
this.uploadProgress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
}
}
</script>
```
在模板中,我们创建了一个文件输入框和一个提交按钮。当用户选择文件后,我们使用`@change`事件来触发`uploadFile`方法,将文件保存在组件的数据中。
在`submitFile`方法中,我们创建了一个FormData对象,将文件作为参数添加到表单数据中。我们使用Axios库的POST方法将表单数据发送到服务器。
我们还使用了`onUploadProgress`事件来显示上传进度条。在事件处理程序中,我们计算上传文件的百分比,并将其保存在组件数据中,以便在模板中显示。