element-ui upload头像上传

自定义上传

<el-upload class="avatar-uploader" action="https://www.baidu.com/"
       :limit="1"
       :show-file-list="false"
       :with-credentials="true"
       :http-request="imgUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<el-button size="small" type="primary" style="margin: 0 1rem;" @click="uploadAvatar">上传</el-button>

<script>
imgUpload(val) {
  logout(val.file)
  console.log(val.file)
  this.imageUrl = URL.createObjectURL(val.file.raw);
  this.file = val.file
},
uploadAvatar() {
  let file = this.file
  let params = new FormData() //创建form对象
  params.append('file', file) //通过append向form对象添加数据
  // console.log(params.get('uploadFile')) //FormData私有类对象,访问不到,可以通过get判断值是否传进去
  identityUpdateAvatar(params).then(res => {
    console.log(res)
    if (res)
      message({message: '修改成功', type: 'success', this: this})
  })
}
</script>

默认上传

<el-upload
    class="avatar-uploader"
    action="http://****:9999/api.file/post"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :with-credentials="true"
    :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

<script>
handleAvatarSuccess(res, file) {
  this.imageUrl = URL.createObjectURL(file.raw);
  identityDetail(this.userInfo.id).then(res => {
    message({message: '上传成功,头像以更改', type: 'success', this: this})
    localStorage.setItem('userInfo', JSON.stringify(res.data)) // 更新本地用户信息
    this.$store.commit('userInfomu', res.data) // 以荷载的方式调用该方法
    this.userInfo = res.data
    let t;
    t = setInterval(() => {
      this.imageUrl = ''
      clearInterval(t)
    }, 1500)
  })
},
beforeAvatarUpload(file) {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (isJPG || isPNG) {
    if (isLt5M) {
      return true
    } else {
      this.$message.error('上传头像图片大小不能超过 5MB!');
      return false
    }
  } else {
    this.$message.error('上传头像图片只能是 JPG 格式!');
    return false
  }
}
</script>
posted @ 2021-12-01 02:14  lambertlt  阅读(1523)  评论(0编辑  收藏  举报