element-ui的el-upload自定義上傳頭像,並顯示進度條

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
        },
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章