element上传图片转base64
element-admin的Tinymce富文本,上传图片改成本地处理
html
<el-upload :multiple="true" :file-list="fileList" :show-file-list="true" :on-remove="handleRemove" :on-success="handleSuccess" :before-upload="beforeUpload" :headers="tokenHeader" class="editor-slide-upload" action="#" list-type="picture-card"> <el-button size="small" type="primary">点击上传</el-button> </el-upload>
js 主要是在 :before-upload里面处理
1 beforeUpload(file) { 2 this.getBase64(file).then(res => { 3 this.fileBase64 = res 4 }) 5 const _self = this; 6 const _URL = window.URL || window.webkitURL; 7 const fileName = file.uid; 8 this.listObj[fileName] = {}; 9 return new Promise((resolve, reject) => { 10 const img = new Image(); 11 img.src = _URL.createObjectURL(file); 12 img.onload = function () { 13 _self.listObj[fileName] = { 14 hasSuccess: true, 15 uid: file.uid, 16 width: this.width, 17 height: this.height, 18 url: _self.fileBase64 19 }; 20 _self.fileList.push({ 21 url:_self.fileBase64, 22 uid:file.uid 23 }) 24 }; 25 resolve(false); 26 }); 27 }, 28 getBase64(file) { 29 return new Promise(function(resolve, reject) { 30 let reader = new FileReader(); 31 let imgResult = ""; 32 reader.readAsDataURL(file); 33 reader.onload = function() { 34 imgResult = reader.result; 35 }; 36 reader.onerror = function(error) { 37 reject(error); 38 }; 39 reader.onloadend = function() { 40 resolve(imgResult); 41 }; 42 }); 43 }