element-ui的el-upload自定义上传头像,并显示进度条
element
A Vue.js 2.0 UI Toolkit for Web
项目地址:https://gitcode.com/gh_mirrors/eleme/element
免费下载资源
·
element默认的上传头像,并没有进度条的展示,当图片较大或网速较慢时,就会显得卡顿,用户体验很不好。所以就重写了el-upload的上传头像部分,并自定义了上传行为。
效果预览:
根据官方文档,要覆盖默认的行为,要绑定http-request,自定义一个方法来实现。这里使用了el-progress来展示进度条,通过axios的onUploadProgress方法来获取实时的进度。
代码实现:
1、template:
<section>
<img v-if="!progressFlag" class="head-img" :src="imageUrl" />
<div v-show="progressFlag" class="head-img">
<el-progress type="circle" :percentage="progressPercent"></el-progress>
</div>
<el-upload class="img-btn" action="#"
:show-file-list="false" :before-upload="beforeAvatarUpload"
:http-request="uploadImg">
<el-button type="success" plain round size="mini">更改头像</el-button></el-upload>
</section>
script:
uploadImg (f) {
console.log(f)
this.progressFlag = true
let formdata = new FormData()
formdata.append('image', f.file)
axios({
url: baseURL + '/image',
method: 'post',
data: formdata,
headers: {'Content-Type': 'multipart/form-data'},
onUploadProgress: progressEvent => {
// progressEvent.loaded:已上传文件大小
// progressEvent.total:被上传文件的总大小
this.progressPercent = (progressEvent.loaded / progressEvent.total * 100)
}
}).then(res => {
this.imageUrl = res.data.data
if (this.progressPercent === 100) {
this.progressFlag = false
this.progressPercent = 0
}
}).then(error => {
console.log(error)
})
},
// 上传图片前的过滤
beforeAvatarUpload (file) {
const isJPG = file.type === 'image/jpeg'
const isLt2M = (file.size / 1024 / 1024) < 2
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isJPG && isLt2M
},
GitHub 加速计划 / eleme / element
54.06 K
14.63 K
下载
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:2 个月前 )
c345bb45
6 个月前
a07f3a59
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update table.md
* Update transition.md
* Update popover.md 7 个月前
更多推荐
已为社区贡献3条内容
所有评论(0)