1、使用axios上传文件并显示上传进度
2、简单的示例如下
<template>
<div>
<input type="file" ref="fileInput" @change="handleFileChange">
<button @click="uploadFile">上传文件</button>
<div v-if="uploadProgress > 0">
<progress :value="uploadProgress" max="100"></progress>
<span>{{ uploadProgress }}%</span>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
file: null,
uploadProgress: 0,
};
},
methods: {
handleFileChange(event) {
this.file = event.target.files[0];
},
uploadFile() {
const formData = new FormData();
formData.append('file', this.file);
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: (progressEvent) => {
this.uploadProgress = Math.round(progressEvent.loaded / progressEvent.total * 100);
}
}).then(() => {
console.log('文件上传成功!');
}).catch((error) => {
console.error('文件上传失败:', error);
});
},
},
};
</script>
3、在这个例子中,使用了一个<input>
元素来让用户选择要上传的文件。当文件选择完毕后,我们将文件保存在组件的file
属性中。然后,我们在uploadFile
方法中创建一个FormData
对象,并将文件附加到该对象中。最后,我们使用Axios的post
方法将文件上传到服务器,并在请求中指定multipart/form-data
类型的头部。此外,我们还指定了一个onUploadProgress
回调函数,以便在上传过程中更新上传进度。
4、onUploadProgress
是Axios提供的一个回调函数,用于在上传过程中获取上传进度。当您使用Axios上传文件时,Axios会将上传进度作为参数传递给onUploadProgress
函数。在这个例子中,我们使用箭头函数来定义onUploadProgress
函数,该函数接收一个progressEvent
参数,该参数包含有关上传进度的信息。
progressEvent
对象有两个属性:loaded
和total
。loaded
表示已上传的字节数,total
表示要上传的总字节数。我们可以使用这些属性来计算上传进度的百分比,并将其保存在组件的uploadProgress
属性中。在这个例子中,我们使用了Math.round
函数来将上传进度四舍五入为整数。