因為在我的快速開發(fā)框架里需要增加內(nèi)容發(fā)布相關(guān)的功能热监,所以需要使用富文本編輯器捺弦。比較了目前熱門的一些富文本編輯器,最后選定了CKEditor4孝扛。CKEditor4的優(yōu)點是功能強(qiáng)大列吼、插件超多、文檔詳細(xì)苦始、更新及時寞钥。
引入CKEditor4
在官網(wǎng)下載CKEditor4,下載地址 https://ckeditor.com/ckeditor-4/download/陌选,我選擇的是Full Package版本理郑。
html頁面中引入CKEditor4
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>CKEditor Sample</title>
<!-- 引入ckeditor.js文件 -->
<script src="../ckeditor.js"></script>
</head>
<body>
<form>
<textarea name="editor1" id="editor1" rows="10" cols="80">
</textarea>
<script>
// 替換 <textarea id="editor1">為CKEditor實例
// 使用默認(rèn)配置
CKEDITOR.replace( 'editor1' );
</script>
</form>
</body>
</html>
在瀏覽器中打開,效果如下
獲取編輯器文本咨油,使用getData方法
CKEDITOR.instances.editor1.getData()
設(shè)置編輯器初始文本香浩,使用setData方法
CKEDITOR.instances.editor1.setData( '<p>This is the editor data.</p>' );
自定義CKEditor4工具欄
CKEditor的工具欄按鈕可以根據(jù)需求靈活的隱藏、顯示臼勉、分組邻吭、排序。
新建一個CKEditor的自定義配置文件editorConfig.js宴霸。
在下載的程序包里提供了自定義工具欄工具囱晴,目錄是ckeditor\samples\toolbarconfigurator,在瀏覽器里打開index.html瓢谢。
配置好后畸写,點擊Get toolbar config,把生成的配置內(nèi)容復(fù)制到editorConfig.js配置文件里氓扛。
CKEDITOR.editorConfig = function (config) {
config.toolbarGroups = [
{name: 'document', groups: ['mode', 'document', 'doctools']},
{name: 'tools', groups: ['tools']},
{name: 'clipboard', groups: ['clipboard', 'undo']},
{name: 'editing', groups: ['find', 'selection', 'spellchecker', 'editing']},
{name: 'forms', groups: ['forms']},
{name: 'basicstyles', groups: ['basicstyles', 'cleanup']},
{name: 'colors', groups: ['colors']},
{name: 'styles', groups: ['styles']},
{name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi', 'paragraph']},
{name: 'others', groups: ['others']},
{name: 'about', groups: ['about']},
{name: 'links', groups: ['links']},
{name: 'insert', groups: ['insert']}
];
config.removeButtons = 'About,Save,NewPage,Preview,Print,Templates,Find,Replace,SelectAll,Scayt,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Language,BidiRtl,BidiLtr,Flash,Iframe,PageBreak,SpecialChar,Smiley,Cut,Copy,Paste,PasteText,PasteFromWord,CopyFormatting,RemoveFormat,Anchor,Styles,Format,Font,JustifyLeft,JustifyCenter,JustifyRight,JustifyBlock';
};
在html頁面里引入自定義配置文件枯芬。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>CKEditor Sample</title>
<!-- 引入ckeditor.js文件 -->
<script src="../ckeditor.js"></script>
</head>
<body>
<form>
<textarea name="editor1" id="editor1" rows="10" cols="80">
</textarea>
<script>
// 使用自定義配置
var editorConfig = {
customConfig: './samples/editorConfig.js'
};
CKEDITOR.replace( 'editor1', editorConfig);
</script>
</form>
</body>
</html>
在瀏覽器中打開,效果如下
自定義CKEditor4上傳圖片工具
CKEditor4默認(rèn)的上傳圖片功能界面不夠簡潔采郎,很繁重千所。
需要替換為使用Enhanced Image Plugin插件。在 https://ckeditor.com/cke4/addon/image2 下載插件蒜埋,解壓到CKEditor程序包的plugins目錄下淫痰。在editorConfig.js文件中增加如下配置:
config.extraPlugins = 'image2';
在瀏覽器中顯示效果如下,默認(rèn)只支持通過url發(fā)布圖片整份。
需要添加本地圖片上傳功能待错。在editorConfig.js文件中增加如下配置:
// 服務(wù)器端上傳圖片接口URL
config.filebrowserImageUploadUrl='/cms/content/uploadImage';
在瀏覽器中顯示效果如下
editorConfig.js文件完整配置
// CKEDITOR配置文件
CKEDITOR.editorConfig = function (config) {
config.language = 'zh-cn';
config.height = 400;
config.extraPlugins = 'image2';
config.filebrowserImageUploadUrl='/cms/content/uploadImage';
config.toolbarGroups = [
{name: 'document', groups: ['mode', 'document', 'doctools']},
{name: 'tools', groups: ['tools']},
{name: 'clipboard', groups: ['clipboard', 'undo']},
{name: 'editing', groups: ['find', 'selection', 'spellchecker', 'editing']},
{name: 'forms', groups: ['forms']},
{name: 'basicstyles', groups: ['basicstyles', 'cleanup']},
{name: 'colors', groups: ['colors']},
{name: 'styles', groups: ['styles']},
{name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi', 'paragraph']},
{name: 'others', groups: ['others']},
{name: 'about', groups: ['about']},
{name: 'links', groups: ['links']},
{name: 'insert', groups: ['insert']}
];
config.removeButtons = 'About,Save,NewPage,Preview,Print,Templates,Find,Replace,SelectAll,Scayt,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Language,BidiRtl,BidiLtr,Flash,Iframe,PageBreak,SpecialChar,Smiley,Cut,Copy,Paste,PasteText,PasteFromWord,CopyFormatting,RemoveFormat,Anchor,Styles,Format,Font,JustifyLeft,JustifyCenter,JustifyRight,JustifyBlock';
};
服務(wù)器端代碼
上傳圖片接口需要返回如下約定的JSON字符串籽孙。
//上傳成功結(jié)果示例
{
"uploaded": 1,
"fileName": "foo.jpg",
"url": "/files/foo.jpg"
}
//上傳失敗結(jié)果示例
{
"uploaded": 0,
"error": {
"message": "The file is too big."
}
}
上傳圖片接口響應(yīng)模型定義如下:
public class UploadImageResModel {
/**
* 1成功,0失敗
*/
private Integer uploaded;
private String fileName;
private String url;
public Integer getUploaded() {
return uploaded;
}
public void setUploaded(Integer uploaded) {
this.uploaded = uploaded;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
假設(shè)上傳圖片的根目錄是E:/upload/火俄。需要把該目錄做靜態(tài)資源映射犯建,映射到/upload/**路由下。新增配置文件:
@Component
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**")
.addResourceLocations("file:///E:/upload/");
super.addResourceHandlers(registry);
}
}
上傳圖片接口代碼如下
@Controller
@RequestMapping("/cms/content")
public class ContentController {
private static final Logger logger = LoggerFactory.getLogger(ContentController.class);
@PostMapping("/uploadImage")
@ResponseBody
public UploadImageResModel uploadImage(@RequestParam("upload") MultipartFile multipartFile) {
UploadImageResModel res = new UploadImageResModel();
res.setUploaded(0);
if (multipartFile == null || multipartFile.isEmpty())
return res;
//生成新的文件名及存儲位置
String fileName = multipartFile.getOriginalFilename();
String newFileName = UUID.randomUUID().toString()
.replaceAll("-", "")
.concat(fileName.substring(fileName.lastIndexOf(".")));
String fullPath = "E:/upload/".concat(newFileName);
try {
File target = new File(fullPath);
if (!target.getParentFile().exists()) { //判斷文件父目錄是否存在
target.getParentFile().mkdirs();
}
multipartFile.transferTo(target);
String imgUrl = "/upload/".concat(newFileName);
res.setUploaded(1);
res.setFileName(fileName);
res.setUrl(imgUrl);
return res;
} catch (IOException ex) {
logger.error("上傳圖片異常", ex);
}
return res;
}
}
最后瓜客,CKEditor除了支持瀏覽本地圖片的方式上傳圖片适瓦,還支持把圖片拖拽到編輯器方式以及從剪貼板粘貼方式上傳圖片。