1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 【富文本】wangeditor编辑器简单使用(自定义图片上传)

【富文本】wangeditor编辑器简单使用(自定义图片上传)

时间:2021-06-23 08:02:13

相关推荐

【富文本】wangeditor编辑器简单使用(自定义图片上传)

一、wangeditor

官网

二、引入

// 安装npm i wangeditor --save// 使用import E from "wangeditor"const editor = new E("#div1")editor.create()

三、使用

自定义上传图片,先转base64,转blob,上传服务器

<div id="wangeditor"><div ref="editorElem" style="text-align:left;" /></div>

import E from 'wangeditor'import axios from 'axios'// 初始化编辑器updated() {this.setEditor()},// 函数setEditor(){const me = thisthis.editor = new E(this.$refs.editorElem)// 自定义上传图片this.editor.config.customUploadImg = function(resultFiles, insertImgFn) {// resultFiles 是 input 中选中的文件列表// insertImgFn 是获取图片 url 后,插入到编辑器的方法me.filesToBase64(resultFiles)}this.editor.config.menus = [// 菜单配置'head', // 标题'bold', // 粗体'italic', // 斜体'underline', // 下划线'link', // 插入链接'image', // 插入图片'undo', // 撤销'redo' // 重复]this.editor.create()}// 转base64filesToBase64(files) {const _this = thisfiles.map(item => {console.log(item)var reader = new FileReader()reader.onload = function(e) {_this.uploadImg(e.target.result, item)}// 传入一个参数对象即可得到基于该参数对象的文本内容reader.readAsDataURL(item)})},// base64转blobBase64toBlob({base64, success }) {var arr = base64.split(',')var mime = arr[0].match(/:(.*?);/)[1]var bstr = atob(arr[1])var n = bstr.lengthvar u8arr = new Uint8Array(n)while (n--) {u8arr[n] = bstr.charCodeAt(n)}const blob = new Blob([u8arr], {type: mime })success(blob)},// 上传图片uploadImg(base64, file) {const _this = this// 自己的上传地址const uploadUrl = process.env.VUE_APP_BASE_API_UNIVERSAL + '/api/qiniu/upload'const formData = new FormData()this.Base64toBlob({base64,success(blob) {formData.append('file', blob, file.name)formData.append('open', true)// 调用axios上传const config = {headers: {'Content-Type': 'multipart/form-data' }}axios.post(uploadUrl, formData, config).then((res) => {// 根据自己的后台逻辑进行判断if (res.data.code === 0) {_this.$message.success('图片上传成功!')// 上传图片,返回结果,将图片插入到编辑器中_this.editor.cmd.do('insertHtml','<img src="' + res.data.result + '" style="max-width:100%;"/>')} else {_this.$message({message: '文件服务异常,请联系管理员!',type: 'error'})}})}})}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。