vue:点击上传图片,本地预览,并获取图片的基于base64的二进制流

    xiaoxiao2022-07-13  211

    本地预览图片,并获取图片的基于base64的二进制流

    @[TOC](本地预览图片,并获取图片的基于base64的二进制流) ***HTML代码******JS代码*** HTML代码
    <el-form-item label="上传学校主图:"> <input type="file" ref="fileBtn" @change="uploadImg" /> <img :src="imgSrc" class="img" ref="img" /> </el-form-item>

    JS代码


    data(){ return { imgInfo: null, imgSrc: null } }, methods: { async uploadImg() { var that = this; const inputFile = await this.$refs.fileBtn.files[0]; let res; console.log('选了图片'); console.log(inputFile); this.inputFile = inputFile; if (this.inputFile) { let inputFile = this.inputFile; if (inputFile.type !== 'image/jpeg' && inputFile.type !== 'image/png' && inputFile.type !== 'image/gif') { alert('不是有效的图片文件!'); return; } this.imgInfo = Object.assign({}, this.imgInfo, { name: inputFile.name, size: inputFile.size, lastModifiedDate: inputFile.lastModifiedDate.toLocaleString() }); console.log(this.imgInfo); const reader = new FileReader(); res = reader.readAsDataURL(this.inputFile); console.log('我想想要获取流'); reader.onloadend = function() { // var strBase64 = reader.result.substring(84); var strBase64 = reader.result.substring(0); console.log(strBase64); }; reader.onload = function(e) { console.log(e); that.imgSrc = this.result; // 注意:这里的this.result中,这个this不是vue实例,而是reader对象,所以之前用that接收vue示例 that.imgSrc }; } else { return; } } }
    最新回复(0)