vue 集成tinymce2实现图片,视频以及文件的上传
1. 安装插件
(1)安装tinymce
npm install tinymce -S
(2)安装tinymce-vue
npm install @tinymce/tinymce-vue@3.0.1 -S
2. 复制静态文件到public
目录
资源下载路径:https://download.csdn.net/download/weixin_44021888/88063970?spm=1001.2014.3001.5503
3. 新建组件:tinymce
<template><div class="tinymce-box"><Editor v-model="contentValue" :init="init" :disabled="disabled" @onClick="onClick" :key="tinymceFlag"/></div>
</template><script>
//引入tinymce编辑器
import Editor from '@tinymce/tinymce-vue'//引入node_modules里的tinymce相关文件文件
import tinymce from 'tinymce/tinymce' //tinymce默认hidden,不引入则不显示编辑器
import 'tinymce/themes/silver' //编辑器主题,不引入则报错
//import 'tinymce/icons/default' //引入编辑器图标icon,不引入则不显示对应图标// 引入编辑器插件(基本免费插件都在这儿了)
import 'tinymce/plugins/advlist' //高级列表
import 'tinymce/plugins/anchor' //锚点
import 'tinymce/plugins/autolink' //自动链接
import 'tinymce/plugins/autoresize' //编辑器高度自适应,注:plugins里引入此插件时,Init里设置的height将失效
import 'tinymce/plugins/autosave' //自动存稿
import 'tinymce/plugins/charmap' //特殊字符
import 'tinymce/plugins/code' //编辑源码
import 'tinymce/plugins/codesample' //代码示例
import 'tinymce/plugins/directionality' //文字方向
import 'tinymce/plugins/emoticons' //表情
import 'tinymce/plugins/fullpage' //文档属性
import 'tinymce/plugins/fullscreen' //全屏
import 'tinymce/plugins/help' //帮助
import 'tinymce/plugins/hr' //水平分割线
import 'tinymce/plugins/image' //插入编辑图片
import 'tinymce/plugins/importcss' //引入css
import 'tinymce/plugins/insertdatetime' //插入日期时间
import 'tinymce/plugins/link' //超链接
import 'tinymce/plugins/lists' //列表插件
import 'tinymce/plugins/media' //插入编辑媒体
import 'tinymce/plugins/nonbreaking' //插入不间断空格
import 'tinymce/plugins/pagebreak' //插入分页符
import 'tinymce/plugins/paste' //粘贴插件
import 'tinymce/plugins/preview'//预览
import 'tinymce/plugins/print'//打印
import 'tinymce/plugins/quickbars' //快速工具栏
import 'tinymce/plugins/save' //保存
import 'tinymce/plugins/searchreplace' //查找替换
// import 'tinymce/plugins/spellchecker' //拼写检查,暂未加入汉化,不建议使用
import 'tinymce/plugins/tabfocus' //切入切出,按tab键切出编辑器,切入页面其他输入框中
import 'tinymce/plugins/table' //表格
import 'tinymce/plugins/template' //内容模板
import 'tinymce/plugins/textcolor' //文字颜色
import 'tinymce/plugins/textpattern' //快速排版
import 'tinymce/plugins/toc' //目录生成器
import 'tinymce/plugins/visualblocks' //显示元素范围
import 'tinymce/plugins/visualchars' //显示不可见字符
import 'tinymce/plugins/wordcount' //字数统计
import Cookies from 'js-cookie'export default {name: 'TEditor',components: {Editor},props: {value: {type: String,default: ''},disabled: {type: Boolean,default: false},plugins: {type: [String, Array],default: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern autosave '},toolbar: {type: [String, Array],default: 'fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | image link media|\styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \table image charmap hr pagebreak insertdatetime print preview | code selectall searchreplace visualblocks | indent2em lineheight formatpainter axupimgs'},},data(){return {tinymceFlag: 1,init: {media_url_resolver: function (data, resolve) {console.log("data:", data)console.log("resolve:", resolve)try {let videoUri = encodeURI(data.url);let embedHtml = `<p><spanclass="mce-object mce-object-video"data-mce-selected="1"data-mce-object="video"data-mce-p-width="100%"data-mce-p-height="auto"data-mce-p-controls="controls"data-mce-p-controlslist="nodownload"data-mce-p-allowfullscreen="true"data-mce-p-src=${videoUri} ><video src=${data.url} width="100%" height="auto" controls="controls" controlslist="nodownload"></video></span></p><p style="text-align: left;"></p>`;resolve({ html: embedHtml });} catch (e) {resolve({ html: "" });}},language_url: '/tinymce/langs/zh_CN.js', //引入语言包文件language: 'zh_CN', //语言类型skin_url: '/tinymce/skins/ui/oxide', //皮肤:浅色// skin_url: '/tinymce/skins/ui/oxide-dark',//皮肤:暗色plugins: this.plugins, //插件配置toolbar: this.toolbar, //工具栏配置,设为false则隐藏// menubar: 'file edit', //菜单栏配置,设为false则隐藏,不配置则默认显示全部菜单,也可自定义配置--查看 http://tinymce.ax-z.cn/configure/editor-appearance.php --搜索“自定义菜单”fontsize_formats: '12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px', //字体大小font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;', //字体样式//自带默认字体:'Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats'lineheight_formats: "0.5 0.8 1 1.2 1.5 1.75 2 2.5 3 4 5", //行高配置,也可配置成"12px 14px 16px 20px"这种形式height: 400, //注:引入autoresize插件时,此属性失效placeholder: '在这里输入文字',branding: false, //tiny技术支持信息是否显示resize: false, //编辑器宽高是否可变,false-否,true-高可变,'both'-宽高均可,注意引号// statusbar: false, //最下方的元素路径和字数统计那一栏是否显示elementpath: false, //元素路径是否显示// relative_urls: false, //false: tinymce将不再自动将文件路径由绝对转为相对// convert_urls: false, //false: tinymce将不再自动处理文件路径content_style: "img {max-width:100%;}", //直接自定义可编辑区域的css样式// content_css: '/tinycontent.css', //以css文件方式自定义可编辑区域的css样式,css文件需自己创建并引入// images_upload_url: '/apib/api-upload/uploadimg', //后端处理程序的url,建议直接自定义上传函数image_upload_handler,这个就可以不用了// images_upload_base_path: '/demo', //相对基本路径--关于图片上传建议查看--http://tinymce.ax-z.cn/general/upload-images.phppaste_data_images: true, //图片是否可粘贴images_upload_handler: (blobInfo, success, failure) => {if(blobInfo.blob().size/1024/1024>3){failure("上传失败,图片大小请控制在 3M 以内")}else{this.uploadFileData(blobInfo.blob(), success,) }},// 用于上传文件file_picker_callback: function(callback, value, meta) {let url = `${window.SITE_CONFIG['apiURL']}/resource/o_upload?token=${Cookies.get('token')}`//文件if(meta.filetype == 'media' || meta.filetype == 'file'){ let input = document.createElement('input');//创建一个隐藏的inputinput.setAttribute('type', 'file');let that = this;input.onchange = function(){let file = this.files[0];//选取第一个文件let chunkSize = 1024 * 1024 * 10; // 每个块的大小(字节),10Mlet fileSize = file.size; // 文件的总大小let totalChunks = Math.ceil(fileSize / chunkSize); // 文件被分成的总块数let chunkNumber = 0; // 当前上传的块的编号let startByte = 0; // 当前上传块的起始字节位置let endByte = chunkSize; // 当前上传块的结束字节位置(不包括)uploadChunk()function uploadChunk() {let chunk = file.slice(startByte, endByte); // 获取当前上传块的内容let params = new FormData()//params.append('file',blobInfo.blob())params.append('file', chunk);params.append("chunkNumber", chunkNumber);params.append("totalChunks", totalChunks);params.append("fileName", file.name);const xhr = new XMLHttpRequest();xhr.open("POST", url, true);// 监听XMLHttpRequest对象的事件xhr.onload = function() {if (xhr.status === 200) {// 上传成功,继续上传下一块chunkNumber++;startByte = endByte;endByte = Math.min(startByte + chunkSize, fileSize);if (startByte < fileSize) {uploadChunk();} else {// 所有块上传成功// 上传的图片callback(`${window.SITE_CONFIG['apiURL']}` +JSON.parse(xhr.response).data.resourceUrl , { title: file.name })}} else {// 上传失败,尝试重传当前块console.error(xhr.statusText);setTimeout(uploadChunk, 1000);}};xhr.onerror = function() {// 网络错误,尝试重传当前块console.error(xhr.statusText);setTimeout(uploadChunk, 1000);};// 发送POST请求xhr.send(params);}}//触发点击input.click();}},},contentValue: this.value}},watch: {value (newValue) {this.contentValue = newValue},contentValue (newValue) {this.$emit('input', newValue)},},activated() {// 每次都给编辑器改变不同的key值使其每次切换页面都重新加载,防止无限递增this.tinymceFlag=this.tinymceFlag===0?1 : 0 ;},mounted(){tinymce.init({})},methods: {// 添加相关的事件,可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available eventsonClick(e){this.$emit('onClick', e, tinymce)},//清空内容clear(){this.contentValue = ''},uploadFileData(file, success) {let url = `${window.SITE_CONFIG['apiURL']}/resource/o_upload?token=${Cookies.get('token')}`let chunkSize = 1024 * 1024 * 10; // 每个块的大小(字节),10Mlet fileSize = file.size; // 文件的总大小let totalChunks = Math.ceil(fileSize / chunkSize); // 文件被分成的总块数let chunkNumber = 0; // 当前上传的块的编号let startByte = 0; // 当前上传块的起始字节位置let endByte = chunkSize; // 当前上传块的结束字节位置(不包括)uploadChunk()function uploadChunk() {let chunk = file.slice(startByte, endByte); // 获取当前上传块的内容let params = new FormData()//params.append('file',blobInfo.blob())params.append('file', chunk);params.append("chunkNumber", chunkNumber);params.append("totalChunks", totalChunks);params.append("fileName", file.name);const xhr = new XMLHttpRequest();xhr.open("POST", url, true);// 监听XMLHttpRequest对象的事件xhr.onload = function() {if (xhr.status === 200) {// 上传成功,继续上传下一块chunkNumber++;startByte = endByte;endByte = Math.min(startByte + chunkSize, fileSize);if (startByte < fileSize) {uploadChunk();} else {// 所有块上传成功// 上传的图片success(`${window.SITE_CONFIG['apiURL']}` +JSON.parse(xhr.response).data.resourceUrl) }} else {// 上传失败,尝试重传当前块console.error(xhr.statusText);setTimeout(uploadChunk, 1000);}};xhr.onerror = function() {// 网络错误,尝试重传当前块console.error(xhr.statusText);setTimeout(uploadChunk, 1000);};// 发送POST请求xhr.send(params);}}},
}
</script>
注意:如果上传过后的视频,只有一张图片的占位符,就把plugins和toolbar这两个属性里面的media去掉就可以了
plugins: {type: [String, Array],default: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern autosave '
},
toolbar: {type: [String, Array],default: 'fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \table image charmap hr pagebreak insertdatetime print preview | code selectall searchreplace visualblocks | indent2em lineheight formatpainter axupimgs'
}