Java教程

element-ui upload头像上传

本文主要是介绍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>
这篇关于element-ui upload头像上传的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!