解决Vue input[type='file'] change事件无法上传相同文件的问题

解决Vue input[type=‘file’] change事件无法上传相同文件的问题

== 话不多说,上代码 ==

  • html
<input
   ref="fileInput"
   type="file"
   accept="image/*"
   style="display: none"
   @change="getFile">
<el-button size="mini" type="primary" @click="addLogo">嵌入logo</el-button>
<el-button size="mini" @click="removeLogo">撤销logo</el-button>   
  • js
// 嵌入logo
    addLogo() {
      this.$refs.fileInput.click()
    },
// 调用change方法    
    getFile(event) {
      const files = event.target.files || null
      const fileReader = new FileReader() // 内置方法new FileReader()   读取文件
      fileReader.addEventListener('load', () => {
        this.imageUrl = fileReader.result
        this.qrCode.clear()
        this.qrCode2.clear()
        this.options2['logo'] = this.imageUrl
        this.options['logo'] = this.imageUrl
        this.qrCode = new QRCode(this.$refs['QRCode'], this.options)
      })
      fileReader.readAsDataURL(files[0])
    },
   // 撤销logo
    removeLogo() {
      this.options.logo = ''
      this.options2.logo = ''
      this.qrCode.clear()
      this.qrCode2.clear()
      this.qrCode = new QRCode(this.$refs['QRCode'], this.options)
    },    

== 当我点击嵌入logo,再撤销logo后,再次嵌入同一张logo时,发现不起作用,logo没有嵌入进来,后来明白,是因为我们在嵌入logo地址后,需要将logo地址清空,以便下次嵌入再次写入logo图片路径,这时: ==

 getFile(event) {
      const files = event.target.files || null
      const fileReader = new FileReader() // 内置方法new FileReader()   读取文件
      fileReader.addEventListener('load', () => {
        this.imageUrl = fileReader.result
        this.qrCode.clear()
        this.qrCode2.clear()
        this.options2['logo'] = this.imageUrl
        this.options['logo'] = this.imageUrl
        this.qrCode = new QRCode(this.$refs['QRCode'], this.options)
      })
      fileReader.readAsDataURL(files[0])
      this.$refs.fileInput.value = null  //我们需要加一个把当前文件路径清空的方法
    },
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值