Vue.js中利用axios实现文件上传进度实时更新

XHR二级增加了progress事件,我们可以据此在浏览器接收新数据期间添加实时数据进度条,从而使得交互更加友好

Vue模板

1
2
<div class="progress" @click="upload"
:style="{backgroundImage:'linear-gradient(to right,#C0C7CB 0%,#C0C7CB ' + progress + ',#E1E6E9 ' + progress + ',#E1E6E9 100%)'}">

Vue JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var form = new FormData()
form.append('file', vm.$refs.upload.files[0])
form.append('name', name)
var config = {
onUploadProgress: progressEvent => {
var complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
this.progress = complete
},
headers: {
'Content-Type': 'multipart/form-data'
}
}
axios.post(`api/upload_file`,
form, config).then((res) => {
if (res.data.status === 'success') {
console.log('上传成功')
}
})

关键点在于progress事件,而axios对ajax封装之后需要在axios的config参数里面定义事件处理函数

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :