解决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 //我们需要加一个把当前文件路径清空的方法
},