vue上传头像并且支持上传大小验证

一、html代码:
 <el-upload :show-file-list="false" :http-request="uploadFile" 
list-type="picture-card" :limit="1" accept=".png"  class="el-upload" :before-upload="beforeAvatarUpload">
    <div class="el-upload--picture-card">
        <img v-if="path" :src="(host || '') + avatar" class="avatar card" />  
         <i v-else class="el-icon-plus avatar-uploader-icon "></i>
     </div>
  </el-upload>
  <div class="text">
      <p>大小不超过10MB</p>
  </div>
二、js代码
data数据:
            host: null,
            avatar: null,
            path: null,
            avatarLocal: null,
校验图片大小: 
 beforeAvatarUpload(file) {
            // console.log(file, 'file====上传前=');
            // file.size < 10 * 1024 * 1024
            const isLtM = file.size / 1024 / 1024 < 10;
            if (!isLtM) {
                this.$message.error("上传头像图片大小不能超过 10MB!");
            }
            return isLtM
        },
上传图片:
 uploadFile(params) {
            console.log(params, "覆盖上传");
            let formdata = new FormData();
            const _file = params.file;
            formdata.append("file", _file);
            UserAPI.GameimageUpload(formdata).then((res) => {
                // console.log(res, 'res====');
                if (res.data.code === 0) {
                    this.path = res.data.data.host + res.data.data.path;
                    this.host = res.data.data.host;
                    this.avatar = res.data.data.path;
                    // console.log(this.path, '===', this.host, '===', this.avatar);
                    const userDataString = localStorage.getItem('user');
                    const userData = JSON.parse(userDataString);
                    userData.avatar = this.path;
                   // localStorage.setItem('user', JSON.stringify(userData));
                    this.$store.dispatch('user/setUser', {...JSON.parse(localStorage.getItem('user')), avatar: this.path });

                    // this.$emit('loginUser_')
                    this.$message.success(res.data.msg);

                    // this.updateVisible(false);
                }

            });

        },

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值