vue前端上传图片并回显,同时获取文件的base64编码
<el-form-item label="部位缩略图:" required> <div class="upload-img" style="width: 148px; height: 100px;" > <input type="file" ref="fileBtn" @change="uploadImg" /> <img v-if="imgSrc" :src="imgSrc" class="img" ref="img" style="width: 100px;height: 100px" /> </div> </el-form-item>
data() { return { imgInfo: null, imgSrc: null }; },
methods: { uploadImg() { const that = this const inputFile = this.$refs.fileBtn.files[0] let res = '' this.inputFile = inputFile if (this.inputFile) { let inputFile = this.inputFile if (inputFile.type !== 'image/jpeg' && inputFile.type !== 'image/png' && inputFile.type !== 'image/gif') { net.message(this, "不是有效的图片文件!", "warning"); return } if (inputFile.size > 1024*20) { net.message(this, "请上传小于 12KB 的图片 !", "warning"); return } this.imgInfo = Object.assign({}, this.imgInfo, { name: inputFile.name, size: inputFile.size, lastModifiedDate: inputFile.lastModifiedDate.toLocaleString() }) const reader = new FileReader() res = reader.readAsDataURL(this.inputFile) reader.onloadend = function() { const strBase64 = reader.result.substring(0); // that.strBase64 = strBase64 } reader.onload = function(e) { // console.log(e); that.imgSrc = this.result } } else { return } }, }