ckeditor的扩展功能,由于编辑器的上传图片一次只能上传一张,因项目需要添加一个多图上传功能
1、ckeditor/plugins/下新建一个uploadImg的目录,并且在里面创建一个plugin.js,把插件的图标放在icons文件夹里(必须命名为icons)
2、注册插件,plugin.js代码如下
var httpUrl = 'XXXXX'; // 图片上传路径
CKEDITOR.plugins.add( 'uploadImg', { // 注册名为uploadImg的插件
icons: 'uploadImg', // 按钮的图标名
init: function( editor ) {
editor.addCommand( 'insertUploadImg', {
exec: function( editor ) {
// 此处定义点击按钮时的行为
// 实现选择的图片上传到服务器,然后将返回的内容添加到编辑器里
var $file = document.createElement('input');
$file.type = 'file';
$file.accept = 'image/*';
$file.multiple = 'multiple';
$file.click();
$file.addEventListener('change',function(e){
var fileList = e.target.files;
if(fileList.length>0) {
let formData = new FormData();
for( var i = 0 ; i < fileList.length ; i++ ){
formData.append('files[]',fileList[i]);
}
let xhr = new XMLHttpRequest(); //创建异步对象
xhr.open('post', httpUrl,true);
xhr.setRequestHeader('Authorization', localStorage.getItem('token'));
xhr.send(formData);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
let result = xhr.responseText;
if (typeof result == 'string') {
let res = JSON.parse(result)
if(res.code =='200'){
//返回图片的url插入到编辑器中
res.data.forEach(function (item,index) {
editor.insertHtml("<p><img src="+item.url+"></p>");
})
}else {
alert(res.message)
}
}
}
}
}
})
}
});
// 添加按钮到编辑器
editor.ui.addButton( 'uploadImg', {
label: '多图上传',
command: 'insertUploadImg',
toolbar: 'insert',
});
}
});
3、在ckeditor/config.js配置toolbar,把自定义的插件显示出来
4、在调用editor的地方添加自定义插件
this.editor = CKEDITOR.replace( 'editor1',{
filebrowserImageUploadUrl: _this.$baseLink + '/admin/upfile/rich',
removeDialogTabs:'image:advanced;image:Link',
image_previewText:' ',
height: 400,
extraPlugins: ['uploadImg'], //加入这行代码
});
CKEDITOR.plugins.addExternal('uploadImg', '/static/ckeditor/plugins/uploadImg/', 'plugin.js'); //加入这行代码
CKEDITOR.instances.editor1.on('change', e => {
_this.formDetail = _this.editor.document.getBody().getHtml();
});
最后效果