场景:后端需要将上传的图片文件作为base64字符串的方式传参给他。
html代码
<div class="upload_box"><el-uploadclass="upload-demo"ref="upload"action="#":show-file-list="false":http-request="(file) => {return httpRequest(file, item);}"style="display: inline-block"><imgv-if="item.darkBg":src="'data:image/jpg;base64,' + item.darkBg"class="avatar"/><i v-else class="el-icon-plus avatar-uploader-icon"></i></el-upload></div>
js代码
httpRequest(data, item) {// 转base64this.getBase64(data.file).then((resBase64) => {item.darkBg = resBase64.split(",")[1];});},// 转base64编码getBase64(file) {this.dialogVisible = false;return new Promise((resolve, reject) => {let reader = new FileReader();let fileResult = "";reader.readAsDataURL(file); //开始转reader.onload = function () {fileResult = reader.result;};//转失败reader.onerror = function (error) {reject(error);};//转结束 resolve 出去reader.onloadend = function () {resolve(fileResult);};});},