上传头像预览头像

141 阅读1分钟

给input type="file"注册change事件onChangeFile,设置ref属性,并隐藏display: none,

用button按钮通过点击事件onclick获取input type="file",模拟点击input --> $refs.ref值.click()触发点击input,进而触发change事件

如果接口文档需要base64的字符串

onChangeFile (e) {
  const fileList = e.target.files
  if (fileList.length > 0) {
    // 选择了图片
    console.log(fileList[0])
    // 将图片转化为base64的字符串  FileReader
    const reader = new FileReader()
    // readAsDataURL将文件对象的数据读取到reader中,转化为base64的字符串
    reader.readAsDataURL(fileList[0])
    // load监听读取完成  reader.result
    reader.addEventListener('load', () => {
      console.log(reader.result)
      this.avatar = reader.result
    })
  } else {
    // 没有选中图片
    this.avatar = ''  // 在data中定义avatar: '', 接收base64字符串,属性绑定img的src属性 :src="avatar"
  }

如果接口文档需要的是对象

// 获取图片
onChangeFile (e) {
  const fileList = e.target.files
  if (fileList.length > 0) {
    // 选择了图片
    console.log(fileList[0])
    this.pubForm.cover_img = fileList[0] // 定义cover_img: null,

    // URL.createObjectUR 能够将图片对象 存储到程序的内存中,返回一个地址
    //  blob:http://localhost:8082/3303a319-af36-4917-baed-82f1181141fc
    const url = URL.createObjectURL(fileList[0])
    console.log(url, '.createObjectURL')
    this.$refs.imgRef.setAttribute('src', url)
  } else {
    // 没有选中图片
    this.pubForm.cover_img = null
    this.$refs.imgRef.setAttribute('src', defaultImg) // defaultImg是我import 导入的 文件夹里面的一个图片
  }
}