头像上传(限制大小,格式,尺寸)

页面展示效果
在这里插入图片描述
HTML部分代码`

<div class="LeaderBuild_BaseInfo">
    <div class="main_left">
      <div class="main_left_title">
        <div>基本信息</div>
      </div>
      <div class="main_left_touxiang marginTop" @click="clickUpload">
        <span v-if="!showImg">上传照片</span>
        <img :src="imageUrl" alt="" v-else ref="imgRef">
        <input v-show="false" ref="uploadRef" type="file" @change="uploadFile" />
      </div>
      <div class="main_left_yaoqiu marginTop">
        <div>上传照片要求: </div>
        <div class="main_left_yaoqiu_main">
          上传照片为免冠证件照,正面二寸 (35mm*45mm),支持JPG、JPEG、gif、PNG格式,大小为2MB以下。
        </div>
      </div>
    </div>
  </div>

JS部分

data() {
    return {
      imageUrl: '',
      showImg: false,
    }
  },
  methods: {
  // 因为input的样式不是我需要的,我的方法是首先隐藏input,然后点击上传照片调用input的uploadFile事件
    clickUpload() {
      this.$refs.uploadRef.click();
    },
    uploadFile(e) {
      const file = e.target.files[0];
      const reader = new FileReader();
      let fileResult = '';
      reader.readAsDataURL(file);
      reader.onload = (e) => {
        fileResult = e.target.result;
        this.beforeAvatarUpload(file, fileResult);
      }
    },
    beforeAvatarUpload(file, fileResult) {
      const img = new Image();
      img.src = fileResult;
      img.onload = () => {
        if (img.width / img.height !== 413 / 626) {
          return this.$message.error('请上传2寸照片');
        }
        const imgType = ['image/jpeg', 'image/png', 'image/gif', 'image/jpeg'];
        if (!imgType.includes(file.type)) {
          return this.$message.error('上传头像图片仅支持JPG、JPEG、gif、PNG格式!');
        }

        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          return this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        // imageUrl 即图片src可以用上传文件的url也可以用base64
        // this.imageUrl = URL.createObjectURL(file);
        this.imageUrl = fileResult;
        this.showImg = true;
      }
    },
  },

CSS部分

.LeaderBuild_BaseInfo {
width: 300px;
}
.main_left {
width: 100%;
height: 100%;
border: 1px solid #f0f5ff;
padding: 4%;
color: #606266;
font-size: 0.16rem;
}
.marginTop{
margin-top: 20px;
}
.main_left_title {
color: #585858;
font-weight: bold;
}
.main_left_touxiang {
width: 120px;
height: 150px;
line-height: 150px;
margin: 0 auto;
margin-top: 16px;
background: #F2F5F9;
color: #596B89;
text-align: center;
cursor: pointer;
}
img {
width: 120px;
height: 150px;
}
.main_left_yaoqiu{
color: #C8CCD4;
font-size: 0.14rem;
}
.main_left_yaoqiu_main{
line-height: 2vh;
text-indent: 20px;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值