ps:公司用了vue-quill-editor插件,点击图片上传按钮会直接上传到后台的oss服务器上,但是在运营的时候发现她们有时候会直接从网上复制图片直接粘贴到富文本框,结果很多都是粘贴的base64的图片,当上传的图片过多,内容过长,打开的时候导致图片展示不出来;于是想就得当判断复制的是base64的时候也上传到后台;
1.vue-quill-editor项目安装
npm install vue-quill-editor --save
2.vue-quill-editor引入
可以有两种方式引入,一个是全局的,但是我这个富文本是单独写的一个组件,所以我是在这个组件中引入;
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
3.富文本组件
组件中html代码:
这里id我也是用的传值,如果一个页面同时有两个富文本,如果都用的同一个id的话会报错,因为一个页面中id是唯一的;
el-upload这个element-ui插件的上传
<template>
<div :id="id">
<quill-editor
ref="myQuillEditor"
v-model="contents"
class='editor'
:class="agreementClass"
:options="editorOption"
@blur="onEditorBlur($event)"
@focus="onEditorFocus($event)"
@ready="onEditorReady($event)"
@change="onEditorChange($event)"
/>
<el-upload
v-show="false"
ref="upload"
:headers="headers"
class="upload-demo"
:action="url"
:multiple="isMultiple"
:on-success="upScuccess">
</el-upload>
</div>
</template>
js代码:
这里用dataURLtoBlob这个方法把base64变成file文件再上传,其实如果后台能接收base64图片就可以不用改成file文件,不过因为base64的图片大的话字节会比较长,传输中会容易掉字符。
// 引入富文本编辑器
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
name: 'Richtext',
props:{
width: {
type: Number,
default: () => 100
},
height:{
type: Number,
default: () => 100
},
content: {
type: String,
default: () => ''
},
placeholder: {
type: String,
default: () => '请在这里输入'
},
agreementClass: {
type: String,
default: () => ''
},
id:{
type: String,
default: () => 'lpc-quill' //id会有个默认值,如果页面中只有一个富文本,就可以不用传id
},
isMultiple:{
type:Boolean,
default:false
}
},
components: {
quillEditor
},
data() {
// 工具栏配置
const toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // 加粗,斜体,下划线,删除线
['blockquote', 'code-block'], // 引用,代码块
[{ header: 1 }, { header: 2 }], // 标题,键值对的形式;1、2表示字体大小
[{ list: 'ordered' }, { list: 'bullet' }], // 列表
[{ script: 'sub' }, { script: 'super' }], // 上下标
[{ indent: '-1' }, { indent: '+1' }], // 缩进
[{ direction: 'rtl' }], // 文本方向
[{ size: ['small', false, 'large', 'huge'] }], // 字体大小
[{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
[{ color: [] }, { background: [] }], // 字体颜色,字体背景颜色
[{ font: [] }], // 字体
[{ align: [] }], // 对齐方式
['clean'], // 清除字体样式
['image'] // 上传图片、上传视频
];
return {
url: '文件上传的url',
headers: {},//这里是文件上传需要用的headers
// content: null,
// 富文本编辑器配置
contents:this.content,
editorOption: {
placeholder: this.placeholder,
//主题
theme: "snow",
modules: {
clipboard:{
//处理粘贴时候的自带样式
matchers:[[Node.ELEMENT_NODE,this.HandleCustomMatcher]]
},
toolbar: {
container: toolbarOptions,
handlers: {
image: value => { //这里是上传图片按钮
if (value) {
document.querySelector(`#${this.id} .upload-demo input`).click()
} else {
this.quill.format('image', false)
}
}
}
}
}
}
}
},
methods: {
//内容改变事件
onEditorChange({ quill, html, text }) {
this.contents = html
this.$emit('getValue',this.contents) //这里是返回富文本框的内容;
},
//失去焦点事件
onEditorBlur(quill) {
console.log('editor blur!', quill)
},
//获得焦点事件
onEditorFocus(quill) {
console.log('editor focus!', quill)
},
// 准备富文本编辑器
onEditorReady(quill) {
console.log('editor ready!', quill)
},
upScuccess(res, file) {
// 附件上传
// 富文本图片上传
//这里是单独点击图片上传按钮上传
const quill = this.$refs.myQuillEditor.quill
if (res.msg === 'success') {
//这里是获取图片成功的返回;
const length = quill.getSelection().index // 获取光标所在位置
quill.insertEmbed( length, 'image', res.data.full_path ) // 插入图片
quill.setSelection(length + 1) // 调整光标位置到最后
}else{
this.$message.error('图片插入失败')
}
},
HandleCustomMatcher(node,Delta){ //粘贴内容会调用的方法
if(node.src && node.src.includes('data:image/png;base64,')){ //这里判断是否有base64的图片
const file = this.dataURLtoBlob(node.src);//这个是把base64的图片变成file文件
const formData = new FormData(); //因为传输文件需要用form格式;
formData.append('file', file, new Date().getTime() + '.png')
this.handleUploadIntoField(formData) // 异步 加入上传图片
Delta.ops = [] // 清除掉粘贴内容
}
const length = Delta?.ops?.[0]?.insert?.length || 0
if (length > 200) Delta.ops[0].insert = Delta?.ops?.[0]?.insert.substring(0, 2000)
// 解决粘贴时字数超过限制的问题
return Delta
},
// 粘贴上传图片
handleUploadIntoField (file) {
//const header = this.headers;
request({
url:this.url,
method: 'post',
data: file
})
.then(resData => {
if(resData.code=="00000"){
//上传base64图片成功的
const quill = this.$refs.myQuillEditor.quill;
const length = quill.getSelection().index;
const imgUrl = resData.data.full_path;
quill.insertEmbed(length, 'image', imgUrl);
quill.setSelection(length + 1)
}else{
this.ImgUploadError()
}
})
.catch(err => {
this.ImgUploadError()
})
},
dataURLtoBlob (dataurl) {
const arr = dataurl.split(',')
// 注意base64的最后面中括号和引号是不转译的
const _arr = arr[1].substring(0, arr[1].length - 2)
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(_arr)
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], { type: mime })
},
// 编辑器内 上传图片失败
ImgUploadError (res, file, list) {
this.$message({ type: 'error', message: '图片插入失败', showClose: true })
}
}
}
4.页面引用富文本框
//html
<richtext
:width='600'
:isMultiple="true"
@getValue='formContentChange'
:content='content'
placeholder="请输入商品详情"
agreementClass="agreement-edit"
id="firstOne">
</richtext>
//js
import richtext from '@/components/richtext'
export default {
name: 'addGoods',
components: {
richtext,
},
data() {
return {
content:''
}
},
methods:{
formContentChange(val) { //接收富文本框值得方法
this.content = val;
},
}
5.页面展示富文本内容
ps:我们经常在后台管理用了富文本框上传内容,然后会在H5或者另外的网页中使用;
a.显示的页面同样需要安装vue-quill-editor;
npm install vue-quill-editor --save
b.引用所需的css;
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
c.同时在div上加上class="ql-editor"
<div class="ql-editor" v-html="rull"></div>