最近在用uni-app写跨端的小程序APP应用。其中有富文本的需求,后台使用的vue-cli3+elementUI。vue做技术栈的话还是选择quill-editor比较多。
quill-editor上传图片和视频到服务器
quill-editor默认的图片是base64文件,一般来说,我们都需要保存至自己的服务器或者OSS。
quill-editor上传到服务器的关键是对quill-editor的图片和视频点击事件的劫持,劫持之后自定义一个上传的方法。基本配置在这里就不多做记录。可以按照需求查看文档或者百度。
editorOption: {
theme: "snow", // or 'bubble'
placeholder: "",
modules: {
imageResize: {},
toolbar: {
container: toolbarOptions,
// container: "#toolbar",
handlers: {
//拦截默认的上传方式
image: function(value) {
//当点击图片上传时,value会变为true
if (value) {
// 触发自定义的上传
document.querySelector(".avatar-uploader input").click();
} else {
this.quill.format("image", false);
}
},
video: function(value) {
//当点击视频上传时,value会变为true
if (value) {
// 触发上传
document.querySelector(".video-uploader input").click();
} else {
this.quill.format("video",false);
}
},
}
}
}
},
文件上传的方法在这里就不做过多解释。下面说一下如何将上传之后的文件,插入到富文本中
uploadSuccessVideo(res,file){
// res为文件服务器返回的数据
// 获取富文本组件实例
let quill = this.$refs.myQuillEditor.quill;
// 如果上传成功
if (res.code === 200) {
// 使用getSelection来获取光标所在位置
let length = quill.getSelection().index;
// 插入“video”或者“image” 第三个参数为服务器端返回的地址
quill.insertEmbed(length, "video", res.data);
// 调整光标到最后
quill.setSelection(length + 1);
console.log(this.content)
} else {
this.$message.error("视频插入失败");
}
// loading动画消失
this.quillUpdateImg = false;
},
到这里自定义的文件服务器上传就完成了。
quill-image-resize-modules的使用
图片只有上传可远远不够,因为用户的图片大小规格不一,改变图片大小的需求是肯定会存在的。
这个插件在安装之后的引用遇到了许多问题,类似"Cannot read property 'register' of undefined"、"Cannot read property 'imports' of undefined" ,也百度了许多方案,但是很多行不通。这里记录下解决方案。
首先是quill-image-resize-module的引入,安装过程就不多做解释。
//引入
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css