vue前端实现file转base64照片预览,而后多文件上传(element)

1,829 阅读1分钟

1、upload组件

<el-upload
  :before-upload="handleAvatarSuccess"
  :show-file-list="false"
  class="upload-demo"
  action=""
  style="width: 200px;float: left;margin-right: 10px"
  list-type="picture">
  <div v-if="!imgUrl.front" class="avatar-uploader-icon">
    <i class="el-icon-loading"/>
  </div>
  <img v-if="imgUrl.front" :src="imgUrl.front" width="200px" height="120px" alt="">
  <el-button size="small" style="margin-left: 90px" type="primary">选择图片</el-button>
</el-upload>

2、handleAvatarSuccess中书写逻辑,将file转成base64

// 单张上传正面图片
handleAvatarSuccess(file) {
  const _this = this
  const r = new FileReader()
  r.readAsDataURL(file)
  r.onload = function(e) {
    _this.imgUrl.front = e.target.result
  }
  // this.fileList是一个formdata对象
  this.imgList.append('fileList', file, 'bb')
}

3、点击按钮实现多文件上传

updateIdcard(this.imgList, this.checkData.id).then(res => {
    this.$message.success('上传成功!')
    this.dialogVisible2 = false
  }).catch(err => {
    this.$message.error(err)
  })

微信图片_20200325182734.jpg