求助:如何通过CK Editor搭配Roxy/Foxy File Manager批量插入图片?
实现CKEditor + Roxy File Manager批量插入图片的方案
我之前也碰到过和你一模一样的需求——默认的Roxy确实只能单张插入图片,折腾了一阵终于搞定了,给你分享几个可行的实操方案:
1. 先让Roxy支持图片多选
首先得解决Roxy不能多选文件的问题,这里有两种直观的实现方式:
方式一:添加复选框(用户友好型)
找到Roxy的文件列表模板(比如templates/default.html里的文件项渲染部分),给每个图片项前加个复选框:
<!-- 修改文件项模板,新增复选框 --> <div class="file-item"> <input type="checkbox" class="img-checkbox" data-file-url="{{fileUrl}}"> <img src="{{thumbUrl}}" alt="{{filename}}"> <span class="file-name">{{filename}}</span> </div>
这样用户可以直接勾选需要插入的多张图片,操作起来更直观。
方式二:启用原生快捷键多选(轻量型)
如果不想改模板,也可以通过JS实现按住Ctrl/Shift键多选图片的功能。找到Roxy的核心JS文件(比如fileman.js),修改文件项的点击事件:
// 给每个文件项绑定多选逻辑 document.querySelectorAll('.file-item').forEach(item => { item.addEventListener('click', function(e) { if (e.ctrlKey || e.shiftKey) { this.classList.toggle('selected'); } else { // 非快捷键点击时,取消其他选中项 document.querySelectorAll('.file-item.selected').forEach(selItem => selItem.classList.remove('selected')); this.classList.add('selected'); } }); });
2. 添加批量插入按钮并编写核心逻辑
在Roxy的顶部操作栏加一个「批量插入图片」的按钮,然后编写JS逻辑把选中的图片批量插入到CKEditor中:
第一步:添加按钮
在Roxy的工具栏区域插入按钮:
<button id="batch-insert-btn" class="btn">批量插入图片</button>
第二步:编写批量插入的JS代码
document.getElementById('batch-insert-btn').addEventListener('click', function() { // 收集所有选中的图片URL const selectedImgs = []; // 兼容复选框和快捷键多选两种方式 const selectedElements = document.querySelectorAll('.img-checkbox:checked, .file-item.selected'); selectedElements.forEach(el => { const imgUrl = el.getAttribute('data-file-url') || el.dataset.fileUrl; if (imgUrl) selectedImgs.push(imgUrl); }); if (selectedImgs.length === 0) { alert('请先选择要插入的图片哦~'); return; } // 调用CKEditor的API批量插入图片 if (window.opener && window.opener.CKEDITOR) { const targetEditor = window.opener.CKEDITOR.instances[window.name]; if (targetEditor) { selectedImgs.forEach(url => { // 创建img元素并插入到编辑器 const img = targetEditor.document.createElement('img'); img.setAttribute('src', url); img.setAttribute('alt', '批量插入图片'); targetEditor.insertElement(img); // 可选:每插入一张图片后加个换行 targetEditor.insertText('\n'); }); // 插入完成后关闭Roxy窗口 window.close(); } } });
3. 调整CKEditor配置(确保兼容性)
最后检查下CKEditor的config.js,确保Roxy的路径配置正确,并且允许跨窗口通信:
CKEDITOR.editorConfig = function(config) { // 其他原有配置... config.filebrowserImageBrowseUrl = '/your-roxy-path/index.html?type=image'; // 确保Roxy窗口能正常调用CKEditor的API config.filebrowserWindowFeatures = 'resizable=yes,scrollbars=yes,width=850,height=600'; };
注意事项
- 要保证Roxy的
fileUrl变量正确返回图片的完整可访问路径 - 如果Roxy用了后端语言(比如PHP),不用额外改后端逻辑,只要前端能拿到正确的图片URL就行
- 测试时注意浏览器的跨窗口权限问题,确保Roxy窗口能访问父窗口的CKEditor实例
内容的提问来源于stack exchange,提问作者Nguyễn Quốc Thịnh
相关产品推荐
相关产品推荐

